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.
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.
As the documentation says, all() returns the result of the query as a list.
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).
This should work
User.query.order_by(User.popularity.desc(), User.date_created.desc()).limit(10).all()
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With