首页 > 解决方案 > 在 SQLAlchemy 中使用 selectinload 加载相关对象时的排序顺序

问题描述

有没有办法在使用selectinloadSQLAlchemy 中的选项加载相关对象时指定排序顺序?

我的 SQLAlchemy 版本:1.2.10 我的 python 版本:3.6.6

标签: pythonpython-3.xsqlalchemy

解决方案


一种方法是在映射类中指定关系的默认顺序。在下面的示例中,类似这样的查询query(Example).options(selectinload(Example.related_items))将按列对预先加载的相关项目进行排序id

from sqlalchemy import Column, Integer, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship

Base = 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')

推荐阅读