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

SQLAlchemy从1.4.32升级到2.0.3后load_only用法报错求助

SQLAlchemy 2.x 中 load_only 动态列名的正确用法

在SQLAlchemy 2.0版本中,load_only()不再支持直接传入字符串列名,必须传入ORM映射类的属性对象。你之前的代码错误在于将属性列表直接传给load_only(),而它需要接收多个位置参数,因此需要用*操作符解包属性列表。

正确代码如下:

columns = ['name','address','city']
u_view = UserView.query.options(
    load_only(*[getattr(UserView, c) for c in columns])
).all()

或者使用生成器表达式(内存更高效):

columns = ['name','address','city']
u_view = UserView.query.options(
    load_only(*(getattr(UserView, c) for c in columns))
).all()

补充说明

如果需要避免因列名不存在引发的AttributeError,可以先通过hasattr校验列名:

columns = ['name','address','city']
valid_attrs = [getattr(UserView, c) for c in columns if hasattr(UserView, c)]
u_view = UserView.query.options(load_only(*valid_attrs)).all()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 01:25:54