python - 如何显式定义 subqueryload_all 中使用的查询?

标签 python postgresql sqlalchemy relationships

我正在大量使用 subqueryload/subqueryload_all,并且我遇到了边缘情况,在这种情况下,我往往需要非常明确地定义在 subqueryload 期间使用的查询。例如,我有一种情况,我有帖子和评论。我的查询看起来像这样:

posts_q = db.query(Post).options(subqueryload(Post.comments))

如您所见,我正在加载每个帖子的评论。问题是我不想要所有帖子的评论,我还需要考虑一个已删除的字段,并且需要按创建时间降序排列。我观察到这样做的唯一方法是在帖子和评论之间的 relationship() 声明中添加选项。我宁愿不这样做,b/c 这意味着此后不能在任何地方重复使用该关系,因为我在应用程序中的其他地方可能不适用这些约束。

我想做的是明确定义 subqueryload/subqueryload_all 用来加载帖子评论的查询。我读到了 DisjointedEagerLoading here ,看起来我可以简单地定义一个接受基本查询的特殊函数,以及一个加载指定关系的查询。这是应对这种情况的好方法吗?以前有人遇到过这种边缘情况吗?

最佳答案

答案是您可以在PostComment 之间定义多种关系:

class Post(...):
    active_comments = relationship(Comment,
         primary_join=and_(Comment.post_id==Post.post_id, Comment.deleted=False),
         order_by=Comment.created.desc())

那么你应该能够通过该关系进行子查询加载:

posts_q = db.query(Post).options(subqueryload(Post.active_comments))

您仍然可以在别处使用现有的 .comments 关系。

关于python - 如何显式定义 subqueryload_all 中使用的查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19108118/

相关文章:

postgresql - 当成功有时导致退出代码为 1 时,我如何可靠地确定 pg_restore 是否成功?

python - 将第一个 django 测试应用程序部署到任何地方(azure 或 heroku)

python - 为什么 python 2.6 不更新我的 numpy 数组?

java - 如何将数据库AWS secret 传递到tomcat context.xml中?

java - 连接到 Postgresql 错误

python - 无法导入名称 'db'(flask、sqlalchemy)

python - 使用sqlalchemy解析python3中的hstore

Python + SQLAlchemy + Oracle + 序列 = 无法插入新行

python - 从 CSV 文件 Python 制作对象

python - 在绘图中创建填充