SQLAlchemy 预加载关系
SQLAlchemy Eager Loading with Relationships
尝试(但失败了)思考如何在以下情况下使用 SQLAlchemy:
假设我有这样一个数据库:
A has a (one -> many) relationship to B
B has a (one -> many) relation to C
如果我想遍历给定 A 的所有 B,我可以这样做:
for b in a.bs:
print "hello"
如果我想遍历间接属于 A 的所有 C,我可以这样做:
for b in a.bs:
for c in b.cs:
print "hello"
但是,我知道最外层循环的每次迭代都会执行新的 SQL 查询。
我的理解是我可以使用子查询加载来防止这种情况发生:
for b in session.query( b ).options( subqueryload( B.c ) ).filter_by( B.a_id == a.id ):
for c in b.cs:
print "hello"
这是最简洁的方法吗?
没有一些语法可以让我从实际的 'a' 对象开始。也许是这样的:
for b in a.bs.options( subqueryload( B.c ) ):
...
非常感谢您的帮助
您可以 subqueryload
像这样的任意连接路径:
session.query(A).options(subqueryload(A.b).subqueryload(B.c))
这使用三个查询,将为 A.b
中的每个 B
加载 A.b
和 B.c
。
尝试(但失败了)思考如何在以下情况下使用 SQLAlchemy:
假设我有这样一个数据库:
A has a (one -> many) relationship to B
B has a (one -> many) relation to C
如果我想遍历给定 A 的所有 B,我可以这样做:
for b in a.bs:
print "hello"
如果我想遍历间接属于 A 的所有 C,我可以这样做:
for b in a.bs:
for c in b.cs:
print "hello"
但是,我知道最外层循环的每次迭代都会执行新的 SQL 查询。
我的理解是我可以使用子查询加载来防止这种情况发生:
for b in session.query( b ).options( subqueryload( B.c ) ).filter_by( B.a_id == a.id ):
for c in b.cs:
print "hello"
这是最简洁的方法吗?
没有一些语法可以让我从实际的 'a' 对象开始。也许是这样的:
for b in a.bs.options( subqueryload( B.c ) ):
...
非常感谢您的帮助
您可以 subqueryload
像这样的任意连接路径:
session.query(A).options(subqueryload(A.b).subqueryload(B.c))
这使用三个查询,将为 A.b
中的每个 B
加载 A.b
和 B.c
。