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

SQLAlchemy异步版with_entities报错:ChunkedIteratorResult无该属性

异步SQLAlchemy中实现同步with_entities的功能

你的错误核心是在执行查询之后调用了with_entities:await session.execute(query)返回的是ChunkedIteratorResult结果对象,它并没有with_entities方法——这个方法属于查询构造器,必须在执行查询前配置完成。

在异步SQLAlchemy的select API里,同步版with_entities的功能直接通过select()函数传入指定字段来实现,字段重命名依然用label()方法。

正确代码示例

# 构造查询时直接指定要返回的字段及别名
query = select(User.id.label('new_id')).offset(offset).limit(limit)
# 执行查询
result = await session.execute(query)
# 获取结果(返回的是元组列表,每个元组对应一条记录的字段值)
users = result.fetchall()

多字段查询示例

如果需要返回多个字段并分别重命名:

query = select(
    User.id.label('new_id'),
    User.username.label('user_name'),
    User.email.label('contact_email')
).offset(offset).limit(limit)
result = await session.execute(query)
users = result.fetchall()

获取字典形式的结果

如果希望返回的结果是字典(键为别名),可以用mappings()方法:

users = result.mappings().all()
# 此时每个元素是类似 {'new_id': 1, 'user_name': 'xxx'} 的字典

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 15:48:29