如果我指定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()