How can I do multiple "order_by" in Flask-SQLAlchemy?

Noé Malzieu picture Noé Malzieu · Apr 3, 2013 · Viewed 38k times · Source

Let's say I have a User model with fields popularity and date_created. I want to do the following query:

SELECT * FROM user ORDER BY popularity DESC, date_created DESC LIMIT 10

In SQLAlchemy, for a single one this works:

User.query.order_by(User.popularity.desc()).limit(10).all()

Should I just add another order_by()? Or put both popularity and date_created in my current order_by()?

I want popularity to have priority on date_created for ordering.

Answer

codegeek picture codegeek · Apr 3, 2013

This should work

User.query.order_by(User.popularity.desc(),User.date_created.desc()).limit(10).all()