SQLAlchemy 在预加载时仅加载集合,而不加载 backref
例如(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)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这就是
contains_eager()
< /a> 选项用于。请尝试以下操作:That's what
contains_eager()
option is for. Try the following: