Skip to main content
 首页 » 编程设计

python之在 SQLAlchemy 中使用 selectinload 加载相关对象时的排序顺序

2024年12月31日8davidwang456

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

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

请您参考如下方法:

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