如何用SQLAlchemy关联查询获取帖子点赞总数及配置自动关联加载
SQLAlchemy 实现帖子投票数统计方案
1. 手动编写查询语句(对应你提供的原生SQL逻辑)
首先导入SQLAlchemy的统计函数:
from sqlalchemy import func
查询单个帖子(id=1)带投票数
# 这里的db是你的Session实例,根据自己的实际变量名调整 post_result = db.query( Post, func.count(Vote.post_id).label("votes") ).join( Vote, Vote.post_id == Post.id, isouter=True # isouter=True对应左连接LEFT JOIN ).filter( Post.id == 1 ).group_by( Post.id ).first() # 取值方式 post_obj = post_result[0] # 帖子对象 vote_num = post_result[1] # 对应帖子的总投票数
查询全部帖子带投票数
去掉filter条件,把first()改成all()即可:
all_post_result = db.query( Post, func.count(Vote.post_id).label("votes") ).join( Vote, Vote.post_id == Post.id, isouter=True ).group_by( Post.id ).all()
2. Post模型配置自动填充投票数
可以用SQLAlchemy的column_property直接在Post模型中定义统计字段,后续无需每次编写自定义查询,直接访问属性即可获取投票数:
首先导入依赖:
from sqlalchemy import column_property, select, func
修改Post模型,新增vote_count属性:
class Post(Base): __tablename__ = "posts" id = Column(Integer, primary_key=True, index=True) title = Column(String, index=True, nullable=False) content = Column(String, nullable=False) published = Column(Boolean) owner_id = Column(Integer, ForeignKey("users.id")) owner = relationship("User") # 新增投票数统计属性,自动关联查询 vote_count = column_property( select(func.count(Vote.post_id)) .where(Vote.post_id == id) .scalar_subquery() )
后续使用时直接访问即可:
# 查询单个帖子 post = db.query(Post).filter(Post.id == 1).first() print(post.vote_count) # 直接输出对应投票数 # 查询全部帖子 all_posts = db.query(Post).all() for p in all_posts: print(p.title, p.vote_count)
注意:如果是批量查询大量帖子,手动写JOIN统计的方式性能会优于
column_property的子查询实现,可根据场景选择合适方案。
内容的提问来源于stack exchange,提问作者Sanjeev Thiyagarajan
相关产品推荐
相关产品推荐

