Skip to main content
 首页 » 编程设计

python之SQLAlchemy 预加载集合大小/计数

2025年05月04日43飞鱼

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

请您参考如下方法:

# 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())