'light request version in sqlalchemy
I have the following models:
class Parent(Base):
__tablename__ = 'parent'
id = Column(Integer, primary_key=True)
children = relationship("Child", backref="parent")
...
class Child(Base):
__tablename__ = 'child'
id = Column(Integer, primary_key=True)
...
There are more attributes for each class. The children are always created first. In my api, I want to send POST requests that creates a Parent with x amount of children. For just a few children, I want the complete child object with all attributes to be in the request body. But there could be a use case where a parent has 100 children. For those, I want to implement a "light" version, where in the request body there would only be the id of each child, instead of the entire object with all attributes for each child.
Is there a built-in way or an example or an official term for such a behavior? I was googling light requests sqlalchemy but choulnd't really find much.
Solution 1:[1]
I think that there is not built-in mechanism of what you desire, because it is not a responsibility of a request how your objects are serialized. For your case I would implement something like that:
class Child(Base):
__tablename__ = 'child'
id = Column(Integer, primary_key=True)
other_attr = Column(String)
def to_dict(self, is_light = False):
if is_light:
return {"id": seld.id}
else:
return {"id": self.id, "other_attr": self.other_attr}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
