Is there a way to specify the sort order when loading related objects using the selectinload
option in SQLAlchemy?
My SQLAlchemy version: 1.2.10 My python version: 3.6.6
Is there a way to specify the sort order when loading related objects using the selectinload
option in SQLAlchemy?
My SQLAlchemy version: 1.2.10 My python version: 3.6.6
One way is just to specify the default ordering of the relationship in your mapped class. In the example below, a query like query(Example).options(selectinload(Example.related_items))
would order the eager loaded related items by the id
column.
from sqlalchemy import Column, Integer, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationshipBase = declarative_base()class Example(Base):__tablename__ = 'examples'id = Column(Integer, primary_key=True)related_items = relationship('RelatedItem', back_populates='example', order_by='RelatedItem.id')class RelatedItem(Base):__tablename__ = 'related_items'id = Column(Integer, primary_key=True)example_id = Column(Integer, ForeignKey('examples.id'), nullable=False)example = relationship('Example', back_populates='related_items')