簡體   English   中英

SQLAlchemy渴望加載集合大小/計數

[英]SQLAlchemy eager loading collection size / count

如果我指定了joinload選項,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()
# 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())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM