首页 > 解决方案 > 使用关系过滤对象而不是在 Flask SQLAlchemy 中查询整个数据库

问题描述

我有两个相关的对象:帖子和评论。一篇文章可以有很多评论。我使用 backref,所以我可以从帖子对象中引用评论列表:

post = Post.query.get(post_id)
all_comments = post.comments # returns all comments of whole post

现在我想按作者过滤这些评论。我希望能够做这样的事情:

post.comments.filter(author_id=author_id)

在 Django 中,我是这样做的:

post.comments.all().filter(author_id=author_id)

但在 Flask 中我无法弄清楚。我不使用以下方法查询所有数据库:

Comment.query.filter_by(post_id=post_id, author_id=author_id)

我该怎么做那个查询?

标签: pythonsqlalchemy

解决方案


在下面试试这个:

Comment.query.join(Post, Comment.post_id == Post.id).filter_by(Post.post_id=post_id, Comment.author_id=author_id).all()

推荐阅读