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 に答える