Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python SqlAlchemy order_by DateTime?

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

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).

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.

Can anyone help?

like image 461
jimt Avatar asked Jan 03 '11 05:01

jimt


3 Answers

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())
like image 118
thirtydot Avatar answered Nov 10 '22 16:11

thirtydot


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

should work.

like image 30
X. Gantan Avatar answered Nov 10 '22 16:11

X. Gantan


You can use like this

from sqlalchemy import desc

db.session.query(MyEntity).order_by(desc(MyEntity.time))
like image 3
Hashir Irfan Avatar answered Nov 10 '22 17:11

Hashir Irfan