1 year ago
#377508
Kendy
Is it possible to employ use logic when back referencing with relationships in SQLAlchemy?
In SQLAlchemy, we can create a table for Parent
and Child
like below -
class Parent(Base):
__tablename__ = 'parent'
id = Column(Integer, primary_key=True)
children = relationship("Child", back_populates="parent")
class Child(Base):
__tablename__ = 'child'
id = Column(Integer, primary_key=True)
parent_id = Column(Integer, ForeignKey('parent.id'))
parent = relationship("Parent", back_populates="children")
age = Column(Integer)
If now I want to add an attribute to Parent
that says oldest_child_age
that uses the linked children's age and then compute the max of all the parent's children. How do I do that? Then ideally when I add to the database another older child, the corresponding parent should have the oldest_child_age
automatically refreshed to that older child (assuming that child is the oldest among all existing children).
Thanks!!
python
database
sqlalchemy
orm
0 Answers
Your Answer