Flask - Return SQLAlchemy results ascending, descending or shuffled
by
Jeremy Canfield |
Updated: October 23 2023
| Flask articles
If you are not familiar with SQLAlchemy, check out my article Getting Started with SQLAlchemy.
This also assumes you are already able to Query records in a table using SQLAlchemy.
By default, the results will be returned in ascending order. order_by can be used to return results in descending order.
from sqlalchemy import desc
data = users.query.filter(users.email.like('%@%')).order_by(desc(users.id))
And here is how you could shuffle the results using func.random.
from sqlalchemy import func
data = users.query.filter(users.email.like('%@%')).order_by(func.random())
Did you find this article helpful?
If so, consider buying me a coffee over at