【问题标题】:Sort order when loading related objects using selectinload in SQLAlchemy在 SQLAlchemy 中使用 selectinload 加载相关对象时的排序顺序
【发布时间】:2018-10-02 07:51:29
【问题描述】:

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

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

【问题讨论】:

    标签: python python-3.x sqlalchemy


    【解决方案1】:

    一种方法是在映射类中指定关系的默认顺序。在下面的示例中,像 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')
    

    【讨论】:

    猜你喜欢
    • 2017-07-01
    • 2021-03-13
    • 2012-03-05
    • 2014-06-29
    • 1970-01-01
    • 2019-08-21
    • 2010-12-21
    • 2020-12-26
    相关资源
    最近更新 更多