python - 使用关系过滤对象而不是在 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)
我该怎么做那个查询?
解决方案
在下面试试这个:
Comment.query.join(Post, Comment.post_id == Post.id).filter_by(Post.post_id=post_id, Comment.author_id=author_id).all()
推荐阅读
- angular - angular2 上带有 FullCalendar 的 eventMouseOver
- laravel - 在 Laravel 中进行分页。为什么只显示 15 个结果?
- r - 用最现值替换值
- .net - 如何在 DataGridView 中编辑和删除数据?
- python - 使用包装脚本中的参数调用 python 脚本
- javascript - 在字符串中的每 3 个字符后添加逗号
- matlab - MATLAB 函数 importdata 行为怪异
- batch-file - 使用 ffprobe 或 ffmpeg 查找分辨率和 fps
- javascript - 如何测试 Tabris 中是否存在文件?
- angular - 如何有条件地设置Angular2组件输入?