SQLAlchemy查询,按关系加入关系和顺序

时间:2013-11-29 17:00:29

标签: python sqlalchemy flask flask-sqlalchemy

我有两个SQLAlchemy模型设置如下:

##############
# 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中,我可以运行:

SELECT post.*, 
       count(like.id) AS num_likes
FROM post
LEFT JOIN like
ON post.id = like.post_id
GROUP BY post.id;

等效的SQLAlchemy命令是什么?

谢谢!

1 个答案:

答案 0 :(得分:10)

从原始查询到Flask-SQLAlchemy的转换非常具有机械性:

db.session.query(Post, db.func.count(Like.id)).outerjoin(Like).group_by(Post.id)