Python SQLAlchemy急切加载集合大小/计数
如果我指定joinedload,SQLAlchemy可以急切地加载集合的内容 选项然而,我有一个例子,我实际上对集合的内容不感兴趣,只对其中的元素数量感兴趣 是否可以让SQLAlchemy作为查询的一部分急切地获取集合的大小 例如,假设我有这样一个结构(真实的例子很长) 现在(再一次抽象地)如果我在墙上得到一个评论列表,我还能得到评论人发布的评论总数吗Python SQLAlchemy急切加载集合大小/计数,python,sqlalchemy,Python,Sqlalchemy,如果我指定joinedload,SQLAlchemy可以急切地加载集合的内容 选项然而,我有一个例子,我实际上对集合的内容不感兴趣,只对其中的元素数量感兴趣 是否可以让SQLAlchemy作为查询的一部分急切地获取集合的大小 例如,假设我有这样一个结构(真实的例子很长) 现在(再一次抽象地)如果我在墙上得到一个评论列表,我还能得到评论人发布的评论总数吗 session.query(Comment) .filter(Comment.wall == wall) .options(jo
session.query(Comment)
.filter(Comment.wall == wall)
.options(joinedload("commenter"))
.options(joinedcount("commenter.comments")) # Here's the mysterious part
.all()
这里的新手,以前从没见过你,所以现在我有地方可以看了。范克斯。
session.query(Comment)
.filter(Comment.wall == wall)
.options(joinedload("commenter"))
.options(joinedcount("commenter.comments")) # Here's the mysterious part
.all()
# alias comments table because it will appear twice in query
comments = aliased(Comment)
result = (session.query(Comment, func.count(comments.id))
.filter(Comment.wall==wall)
.join(Person) # we need to join person table explicitly
.join(comments) # to reach comments table again in another join
.group_by(Comment.id)
# populates relationship using explicitly joined table
.options(contains_eager(Comment.commenter))
.all())