Skip to content Skip to sidebar Skip to footer

SQLAlchemy: Filter The Objects From Relationship When Accessed

Query Statement: Get Children that have their Names start with 'A'. Link Them With their Parents. Schema: I Have a One-to-Many Relationship. Parent(id, Name, children(rel->chi

Solution 1:

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))

Post a Comment for "SQLAlchemy: Filter The Objects From Relationship When Accessed"