python - 在 SQLAlchemy 中使用 selectinload 加载相关对象时的排序顺序
问题描述
有没有办法在使用selectinload
SQLAlchemy 中的选项加载相关对象时指定排序顺序?
我的 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')
推荐阅读
- sql - 不显示表格
- redis - Nifi Redis Sentinel 集成
- javascript - 在 TS 中使用 Jest 模拟段分析
- python - 如何将数据框中的一行的值与另一个数据框中的多行进行比较(包括计算)
- for-loop - 将蛋白质序列的权重与正确的序列配对
- java - 带有字符串和列表的 TreeMap
- python - DietPi - 手动运行脚本有效 - 但从 postboot.d 开始会引发 I/O 错误
- python - 如何使用 python-docx 读取源自 Word 模板的 docx?
- javascript - 自定义文本编辑器未显示“未保存的更改”警告?
- amazon-web-services - 使用 Fargate 将 imgproxy 部署到 AWS