sqlalchemy The ORM Order By


Given a basic model:

class SpreadsheetCells(Base):
    __tablename__ = 'spreadsheet_cells'

    id = Column(Integer, primary_key=True)
    y_index = Column(Integer)
    x_index = Column(Integer)

You can retrieve an ordered list by chaining the order_by method.

query = session.query(SpreadsheetCells).order_by(SpreadsheetCells.y_index)

This could be chained on after a filter,

query = session.query(...).filter(...).order_by(...)

or to further compose an existing query.

query = session.query(...).filter(...)
ordered_query = query.order_by(...)

You can also determine the sort direction in one of two ways:

  1. Accessing the field properties asc and dsc:
query.order_by(SpreadsheetCells.y_index.desc()) # desc
query.order_by(SpreadsheetCells.y_index.asc()) # asc
  1. Using the asc and desc module functions:
from sqlalchemy import asc, desc

query.order_by(desc(SpreadsheetCells.y_index)) # desc
query.order_by(asc(SpreadsheetCells.y_index)) # asc