SQLAlchemy只在加载时加载集合,而不是backref

时间:2010-07-21 10:41:33

标签: sqlalchemy eager-loading

例如(eagerload / joinedload做同样的事情):

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

在关闭会话之前添加以下循环有效(并且没有命中数据库):

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

这很愚蠢。有没有办法改变原始查询,以便它加载关系的两面而不在输出SQL中添加更多连接?

更新如果相关;这是映射

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)

1 个答案:

答案 0 :(得分:4)

这就是contains_eager()选项的用途。请尝试以下方法:

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