Xavier
Xavier

Reputation: 463

SQLAlchemy: Filter the Objects From Relationship When Accessed

class Parent(Base):
    __tablename__ = 'parent'

    id = Column(Integer, primary_key=True)
    Name = Column(String)
    children = relationship("Child", lazy='joined')

class Child(Base):
    __tablename__ = 'child'

    id = Column(Integer, primary_key=True)
    Name = Column(String)

How do I write a Statement to get the Above Result?

A solution that Filters them Once Loaded, I want to Filter them While Loading.

Upvotes: 1

Views: 1929

Answers (1)

Xavier
Xavier

Reputation: 463

Perhaps I should've googl-fu'ed Harder, but this was the result of some searching.

From SQLAlchemy Documentation:

When we use contains_eager(), we are constructing ourselves the SQL that will be used to populate collections. From this, it naturally follows that we can opt to modify what values the collection is intended to store, by writing our SQL to load a subset of elements for collections or scalar attributes.

Resulting in the Statement:

db.Query(Parent).join(Parent.children)\
                .filter(Parent.children.any(Child.Name.like("A%")))\
                .options(contains_eager(Parent.children))

Upvotes: 3

Related Questions