python - SQLAlchemy、Postgres、与 Alchemy 模型的加入变得不同

标签 python sqlalchemy distinct

我对 SQLAlchemy 比较陌生,到目前为止还没有做过任何复杂的事情。我现在需要返回一行的最新“版本”。我可以使用“distinct”返回相关列表,但是我很难让查询返回 SQLAlchemy 模型。

 session.query(Document.document_id,func.max(Document.id)).\
    filter_by(container_id=1,active=True).\
    group_by(Document.document_id).all()

这会返回我需要的 id 列表。但我真正需要的是整个模型。

我确信有一种简单的方法可以加入它。然而它完全让我无法理解。

最佳答案

使用 subquery ,您可以加入:

subq = (session.query(
            # Document.document_id, # do not need this really
            func.max(Document.id).label("max_id")
        )
        .filter(Document.container_id == 1)
        .filter(Document.active == True)
        .group_by(Document.document_id)
        ).subquery("subq")

qry = (session.query(Document)
        .join(subq, Document.id == subq.c.max_id)
        ).all()

关于python - SQLAlchemy、Postgres、与 Alchemy 模型的加入变得不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24477040/

相关文章:

python - 使用polyval时加载网页的问题,使用numpy的polyfit

Python/Tensorflow - 在这种情况下,所有精度值均为 "1"是否正常?

python - SQLAlchemy,同一张表上的一对一关系

python - SQLAlchemy 中不区分大小写的字符串列?

mysql - 在 JOIN 表上应用 DISTINCT 不起作用

java - 与JAVA中的ArrayList不同的值

python - 切片索引必须是整数或 None 或具有 __index__ 方法

python - 感兴趣区域时无类型错误

flask 。 sqlalchemy.exc.InterfaceError : <app. models.Menu 对象位于 0x7f287026dd10>

node.js - Node ,MongoDB( Mongoose )非重复计数