2

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

1 回答 1

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())
于 2013-08-13T17:52:36.837 回答