You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SQLAlchemy如何让query(model).all()返回值元组而非模型实例

SQLAlchemy查询直接返回元组列表的实现方案

下面是几种更简洁的实现方式,按推荐优先级排序:

  • 最高效方案:查询阶段直接指定字段,避免额外实例化开销
    你不需要先查询整个模型实例再转元组,直接在query方法中传入需要的字段,返回结果默认就是元组列表:
s = Session()
# 直接指定要查询的字段,all()返回的直接是元组列表
result = s.query(
    Security.id,
    Security.ticker,
    Security.company,
    Security.sector,
    Security.industry,
    Security.country
).all()
  • 不需要手动列字段的动态方案
    如果需要返回所有字段,不想手动挨个写列名,可以通过模型的__table__.columns属性自动展开所有列:
s = Session()
# *号展开所有字段,直接返回全字段元组列表
result = s.query(*Security.__table__.columns).all()

这个方法适配性最强,后续你给模型加/减字段都不用改查询代码,自动同步字段顺序。

  • 已有实例列表的转换方案
    如果你已经拿到了模型实例列表,不想改查询逻辑,可以用operator.attrgetter批量提取属性,比手动写推导式更简洁:
from operator import attrgetter

# 手动指定字段
getter = attrgetter('id', 'ticker', 'company', 'sector', 'industry', 'country')
result = [getter(instance) for instance in q]

# 动态取全字段写法
getter = attrgetter(*Security.__mapper__.columns.keys())
result = [getter(instance) for instance in q]

内容的提问来源于stack exchange,提问作者Paul Marmagne

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 15:48:04