SQLAlchemy多表查询指定列未返回投票数统计结果问题
问题原因和修复方案
- 你的统计字段没有设置别名,查询结果返回的第一个值就是投票计数,你之前输出内容时没有读取该值;其次当前用的隐式内连接会过滤掉没有投票的帖子,需要改为左连接才能保留0票的内容,另外你需求里要求的
published字段也没有加到查询字段中。 - 修正后的查询代码如下:
all_posts = db.query( func.count(models.Vote.post_id).label("total_votes"), # 给统计字段添加别名方便读取 models.User.username, models.Post.id, models.Post.title, models.Post.content, models.Post.published, # 补充需求要求的published字段 models.Post.created_at # 显式指定左外连接,保留没有对应投票记录的帖子 ).outerjoin( models.User, models.Post.user_id == models.User.id ).outerjoin( models.Vote, models.Vote.post_id == models.Post.id ).group_by( models.User.username, models.Post.id, models.Post.title, models.Post.content, models.Post.published, models.Post.created_at )
- 输出读取说明:查询返回的每条结果都可以通过别名直接获取投票数,比如遍历结果时可以用
item.total_votes拿到对应帖子的总投票数,补充该字段到输出逻辑即可,示例输出如下:
total_votes: 3 username: 'User1' id: 1 title: Title 1 content: Content 1 published: True created_at: '2021-11-18T12:13:09.236169+05:30'
内容的提问来源于stack exchange,提问作者MISHANDLED
相关产品推荐
相关产品推荐

