如何在sqlalchemy中批量加载父级子集的关系?
假设我有两个模型,博客和评论是一对多的关系。
class Blog(Base):
id = Column(Integer, primary_key=True)
comments = relationship("Comment")
class Comment(Base):
id = Column(Integer, primary_key=True)
blog = relationship("Blog")
我可以通过这样的子查询有效地查询博客及其评论
session.query(Blog).filter(...filter_criteria...).options(subqueryload(Blog.comments)).all()
这将发出两个独立的查询-一个用于加载博客,另一个用于加载评论。
如果我已经有一堆已经被查询的博客对象,我该如何加载评论呢?我不能在获取博客时使用subqueryload的原因是,应用程序逻辑使用了需要评论的博客子集。
换句话说,如果我在一个列表中有5个博客对象,有没有一种方法可以有效地加载评论,这样我就可以这样访问它们:
blogs = [b1, b2, b3, b4, b5]
# Do something here to efficiently load comments
for blog in blogs:
blog.comments
转载请注明出处:http://www.932981.com/article/20230526/1935551.html