Python SqlAlchemy order_by DateTime?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4582264/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 16:26:32  来源:igfitidea点击:

Python SqlAlchemy order_by DateTime?

pythonsqlalchemy

提问by jimt

I'm using SqlAlchemy to store some objects with a DateTime field:

我正在使用 SqlAlchemy 来存储一些带有 DateTime 字段的对象:

my_date = Field(DateTime())

I'd like to run a query to retrieve the most recent few objects (Entities with the my_date field that are the most recent).

我想运行一个查询来检索最近的几个对象(最近的具有 my_date 字段的实体)。

I've tried the following:

我尝试了以下方法:

entities = MyEntity.query.order_by(MyEntity.time).limit(3).all()
entities = MyEntity.query.order_by(-MyEntity.time).limit(3).all()

But these queries return the same objects in the same order. The SqlAlchemy documentation notes the use of the '-' to reverse the order, but I'm surely missing something here.

但是这些查询以相同的顺序返回相同的对象。SqlAlchemy 文档指出使用“-”来反转顺序,但我肯定在这里遗漏了一些东西。

Can anyone help?

任何人都可以帮忙吗?

采纳答案by thirtydot

You can do it like this:

你可以这样做:

entities = MyEntity.query.order_by(desc(MyEntity.time)).limit(3).all()

You might need to:

您可能需要:

from sqlalchemy import desc

Here's some documentation.

这是一些文档

Another option is this:

另一种选择是这样的:

stmt = select([users_table]).order_by(users_table.c.name.desc())

回答by X. Gantan

entities = MyEntity.query.order_by(MyEntity.my_date.desc()).limit(3).all()

should work.

应该管用。