如果我指定了joinedload,SQLAlchemy可以急切地加载集合的内容 选项。但是,我有一个案例,我实际上并不感兴趣的是集合的内容,只是其中的元素数量。
是否可以让SQLAlchemy作为查询的一部分急切地获取集合的大小?
例如,假设我有一个类似的结构(真实的例子是冗长的)
class Person:
name = Column(String)
avatarUrl = Column(String)
comments = relation(Comment)
class Wall:
Person for_whom
class Comment
commenter = relation(Person)
wall = relation(Wall)
text = Column(String)
现在(再次抽象地说)如果我在墙上收到评论列表,我还可以获得评论者发布的评论总数吗?
session.query(Comment)
.filter(Comment.wall == wall)
.options(joinedload("commenter"))
.options(joinedcount("commenter.comments")) # Here's the mysterious part
.all()
答案 0 :(得分:1)
# 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())