'Is there any way to filter by the first child using SqlAlchemy?
I'm trying to find a way to filter by the attribute of the first row returned as children.
class Parent(Base):
__tablename__ = "parent_table"
id = Column(Integer, primary_key=True, index=True, autoincrement=True)
children = relationsihp("Child", back_populates="parent")
class Child(Base):
__tablename__ = "child_table"
id = Column(Integer, primary_key=True, index=True, autoincrement=True)
parent_id = Column(Integer, ForeignKey("parent_table"))
type = Column(String(10))
created_at = Column(TIMESTAMP)
parent = relationship("Parent", back_populates="children")
What I need to do is select Parent while selecting their children as well, order the children by created_at
, see if type
of the first row returned(first child, i guess?) is 'type A', and if not, don't select that Parent.
Is it possible to implement this using SqlAlchemy?
At first I tried to add new temporary columns of each child row's 'type' which has value of created_at
but i was not able to make a query comparing two columns of the same record.
Then I tried to use hybrid_property
, which returns type
of the first child as Parent's property. It didn't work as well because it was not allowed to filter by hybrid_property
.(In real case, 'type' is not given. It has to be calculated using other attributes and conditions.)
It would be also highly appreciated if you just give me some hint about making a query using raw SQL syntax.
Thank you.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|