【问题标题】:Filter objects using relationship not querying whole DB in Flask SQLAlchemy [duplicate]使用关系过滤对象而不是在 Flask SQLAlchemy 中查询整个数据库 [重复]
【发布时间】: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


【解决方案1】:

在下面试试这个:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-16
    • 2018-08-22
    • 2017-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-15
    相关资源
    最近更新 更多