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'))
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;
What's the equivalent SQLAlchemy command?
Thanks!
从原始查询到 Flask-SQLAlchemy 的转换非常机械:
db.session.query(Post, db.func.count(Like.id)).outerjoin(Like).group_by(Post.id)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.