Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 987
Noé Malzieu Avatar asked Apr 03 '13 15:04

Noé Malzieu


People also ask

What is the difference between SQLAlchemy and Flask-SQLAlchemy?

One of which is that Flask-SQLAlchemy has its own API. This adds complexity by having its different methods for ORM queries and models separate from the SQLAlchemy API. Another disadvantage is that Flask-SQLAlchemy makes using the database outside of a Flask context difficult.

What does SQLAlchemy all () return?

As the documentation says, all() returns the result of the query as a list.

What does First () do in SQLAlchemy?

Return the first result of this Query or None if the result doesn't contain any row. first() applies a limit of one within the generated SQL, so that only one primary entity row is generated on the server side (note this may consist of multiple result rows if join-loaded collections are present).


2 Answers

This should work

User.query.order_by(User.popularity.desc(), User.date_created.desc()).limit(10).all() 
like image 135
codegeek Avatar answered Sep 25 '22 13:09

codegeek


What you also could do:

from sqlalchemy import and_, or_ User.query.order_by(and_(User.popularity.desc(), User.date_created.desc())).all() 

Note: and_ and or_ are coming from the sqlalchemy library and not from flask_sqlalchemy library. sqlalchemy is a dependency for flask_sqlalchemy, so you should be good.

LTS: You can mix sqlalchemy lib with flask_alchemy lib

like image 26
0x78f1935 Avatar answered Sep 25 '22 13:09

0x78f1935