Chrome Extension

Order by descending records SQLAlchemy

If you are using SQLAlchemy and want to order your records in descending order by some column values then you can use the order_by() method.
#Direct apply on model property
.order_by(UserModel.id.desc())

#by importing desc() method
from sqlalchemy import desc
session.query(UserModel).order_by(desc(UserModel.id)).all()
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place. Check how cool is the tool

There are two ways to order your records in descending order. First by using .desc directly apply to your column name.

self.session.query(
    UserModel
).filter(
    UserModel.role = 'simple'
).order_by(
    UserModel.id.desc()
).all()

If you want to wrap your Model Property inside the desc() method then you will have to import it first.

from sqlalchemy import desc 

self.session.query(
    UserModel
).filter(
    UserModel.role = 'simple'
).order_by(
    desc(UserModel.id)
).all()
Was this helpful?
0 Comments