【发布时间】:2020-07-05 22:26:14
【问题描述】:
我有两个相关的对象:帖子和评论。一篇文章可以有很多评论。我使用 backref,所以我可以从帖子对象中引用评论列表:
post = Post.query.get(post_id)
all_comments = post.comments # returns all comments of whole post
现在我想按作者过滤这些 cmets。我希望能够做这样的事情:
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)
我该如何进行查询?
【问题讨论】:
-
这个 author_id=author_id 是什么意思?
-
它不是很漂亮,但它是一样的,你仍然在 Django 中查询“所有的数据库”。只需确保您的评论表在 post_id 和 author_id 上都有索引
-
你试过
post.comments.filter_by(author_id=author_id)吗? -
@AbhishekKulkarni 获取所有由 id 等于 author_id 的人创建的 cmets,因为 post 可以有多个不同用户创建的 cmets。
-
@lalithkumar 是的,不起作用
标签: python sqlalchemy