Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy only loads collection, not backref when eagerloading

For example (eagerload/joinedload do the same thing):

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 doesn't hit the DB):

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

Which is pretty dumb. Is there a way to alter the original query so that it loads both sides of the relation without adding more joins in the output SQL?

update In case it's relevant; here's the mapping

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)
like image 739
Draemon Avatar asked Jul 21 '10 10:07

Draemon


1 Answers

That's what contains_eager() option is for. Try the following:

parents = session.query(Parent).options(joinedload(Parent.children),
                                        contains_eager('children.parent')).all()
like image 144
Denis Otkidach Avatar answered Sep 30 '22 13:09

Denis Otkidach