SQLAlchemy的;订购

时间:2016-03-16 10:51:32

标签: python postgresql sqlalchemy

使用SQLAlchemy ORM查询PostgreSQL(v9.5);如何在按列排序时阻止自动选择;不应选择已排序的列。

希望下面的示例代码能够更加清晰。

示例代码

包含整数'id',整数'object_id'和字符串'text'的表:

id | object_id | text
---------------------
1  | 1         | house
2  | 2         | tree
3  | 1         | dog

以下查询应该将不同的object_id作为自己的id返回最近的text

query = session.query(
    MyTable.object_id.label('id'),
    MyTable.text
).\
    distinct(MyTable.object_id).\
    order_by(MyTable.object_id, MyTable.id.desc())

到目前为止一切顺利;但是当我编译查询时:

print(query.statement.compile(dialect=postgresql.dialect()))

同时选择mytable.idmytable.object_id,因此指定了列id两次:

SELECT DISTINCT ON (mytable.object_id) mytable.object_id AS id,
                                               mytable.text,
                                               mytable.object_id,
                                               mytable.id
FROM mytable
ORDER BY mytable.object_id,
         mytable.id DESC

1 个答案:

答案 0 :(得分:0)

你可以尝试一下。它应该工作:

query = session.query(MyTable.object_id.distinct().label('id'), MyTable.text).order_by(MyTable.object_id, MyTable.id.desc())