【发布时间】:2018-10-02 07:51:29
【问题描述】:
有没有办法在使用 SQLAlchemy 中的selectinload 选项加载相关对象时指定排序顺序?
My SQLAlchemy 版本:1.2.10 我的python版本:3.6.6
【问题讨论】:
标签: python python-3.x sqlalchemy
有没有办法在使用 SQLAlchemy 中的selectinload 选项加载相关对象时指定排序顺序?
My SQLAlchemy 版本:1.2.10 我的python版本:3.6.6
【问题讨论】:
标签: python python-3.x sqlalchemy
一种方法是在映射类中指定关系的默认顺序。在下面的示例中,像 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')
【讨论】: