The following pytest passes, as expected:
from sqlalchemy.orm import contains_eager
@pytest.fixture(scope="function", autouse=True)
def populate_db(test_db: Session):
"""Populate db with a single parent with two children that go to different schools."""
parent_1 = Parent(uuid="1")
child_1 = Child(uuid="2", parent_uuid="1", school="north")
child_2 = Child(uuid="3", parent_uuid="1", school="south")
test_db.add(parent_1)
test_db.commit()
test_db.add(child_1)
test_db.add(child_2)
test_db.commit()
def test_eager(db: Session):
"""Query for parents based off of weather or their child goes to school 'north'."""
parent = db.query(Parent).join(Child).filter(Child.school == "north").first()
# both of the parent children relationships are returned
assert len(parent.children) == 2
parent = db.query(Parent).join(Child).options(contains_eager(Parent.children)).filter(Child.school == "north").first()
# Only one of the parent child relationship returned
assert len(parent.children) == 1
What I would like, is for the behaviour of contains_eager to be applied by default (so in this case the first assertion would be false, since only the 1 parent.children relationship would be returned)
Also, I have many instances where I would want this to be applied, so would prefer not to have to define the relationship path each time .options(contains_eager(Parent.children))
For example if I added a School model, I wouldn't want to be required to update the options with School.children.