SQLAlchemy only loads the collection, not backref when loading

For example (eagerload / joinload does the same):

session = Session()    
parents = session.query(Parent).options(joinedload(Parent.children)).all()
session.close()

print parents[0].children  # This works
print parents[0].children[0].parent  # This gives a lazy loading error

Adding the following loop before closing the session works (and does not end up in the database):

for p in parents:
  for c in p.children:
    c.parent

This is pretty stupid. Is there a way to modify the original query so that it loads both sides of the relationship without adding additional joins to the output SQL?

update If relevant; mapping here

class Parent(Entity):
  __tablename__ = "parent"

  id = Column(Integer, primary_key=True)
  children = relation("Child", backref="parent")

class Child(Entity):
  __tablename__ = "child"

  id = Column(Integer, primary_key=True)
  parentId = Column(Integer, ForeignKey("parent.id"), index=True)
+3
source share
1 answer

What does contains_eager()option mean . Try the following:

parents = session.query(Parent).options(joinedload(Parent.children),
                                        contains_eager('children.parent')).all()
+4
source

Source: https://habr.com/ru/post/1755717/


All Articles