SQLAlchemy 查询、连接关系和按计数排序 [英] SQLAlchemy query, join on relationship and order by count
本文介绍了SQLAlchemy 查询、连接关系和按计数排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个 SQLAlchemy 模型设置如下:
I have two SQLAlchemy models set up as follows:
##############
# Post Model #
##############
class Post(db.Model):
id = db.Column(db.Integer, primary_key = True)
title = db.Column(db.String(250))
content = db.Column(db.String(5000))
timestamp = db.Column(db.Integer)
author_id = db.Column(db.Integer, db.ForeignKey('user.id'))
likes = db.relationship('Like', backref = 'post', lazy = 'dynamic')
###############
# Likes Model #
###############
class Like(db.Model):
id = db.Column(db.Integer, primary_key = True)
voter_id = db.Column(db.Integer, db.ForeignKey('user.id'))
post_id = db.Column(db.Integer, db.ForeignKey('post.id'))
如您所见,有一个帖子模型和一个用户喜欢这些帖子的模型.我想创建一个选择所有帖子的查询,按帖子的喜欢数量排序.在shell中,我可以运行:
As you can see, there's a model for posts and a model for user likes on those posts. I'd like to create a query that selects all posts, ordered by the number of likes that post has. In the shell, I can run:
SELECT post.*,
count(like.id) AS num_likes
FROM post
LEFT JOIN like
ON post.id = like.post_id
GROUP BY post.id;
等效的 SQLAlchemy 命令是什么?
What's the equivalent SQLAlchemy command?
谢谢!
推荐答案
从原始查询到 Flask-SQLAlchemy 的转换非常机械:
The translation from raw query to Flask-SQLAlchemy is pretty much mechanical:
db.session.query(Post, db.func.count(Like.id)).outerjoin(Like).group_by(Post.id)
这篇关于SQLAlchemy 查询、连接关系和按计数排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文