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

如何从SQLAlchemy模型对象提取显式字段生成更新字典?

如何将SQLAlchemy模型对象转换为仅含显式字段的字典用于update操作

表定义

class AppProperties(base):
    __tablename__ = "app_properties"
    key = Column(String, primary_key=True, unique=True)
    value = Column(String)

问题描述

执行以下更新代码时遇到报错:

session = Session()
query = session.query(AppProperties).filter(AppProperties.key == "memory")
new_setting = AppProperties(key="memory", value="1 GB")
query.update(new_setting)

直接传入new_setting会失败,因为update方法要求传入可迭代对象;如果改用query.update(vars(new_setting)),又会包含基类或底层的额外属性,导致数据库不识别这些字段而报错。我们需要把new_setting转换成只包含AppProperties显式定义的key和value字段的字典,即{"key": "memory", "value": "1 GB"},才能正常调用update方法。

可行方案

方案1:手动提取字段(适合字段较少的场景)

直接从对象中取出需要的字段构造字典:

update_data = {
    "key": new_setting.key,
    "value": new_setting.value
}
query.update(update_data)

方案2:用SQLAlchemy的inspect工具(通用方案)

借助SQLAlchemy的inspect工具获取模型定义的所有列,自动生成目标字典,无需手动指定字段:

from sqlalchemy import inspect

# 获取模型的列映射
mapper = inspect(AppProperties)
# 遍历列,提取对应字段的值
update_data = {col.key: getattr(new_setting, col.key) for col in mapper.columns}
query.update(update_data)

这个方法会自动过滤掉模型中未显式定义的属性,只保留表内存在的字段。

方案3:给模型类添加to_dict方法(复用性强)

在AppProperties类中添加一个方法,方便后续随时将对象转换为符合要求的字典:

from sqlalchemy import inspect

class AppProperties(base):
    __tablename__ = "app_properties"
    key = Column(String, primary_key=True, unique=True)
    value = Column(String)

    def to_dict(self):
        # 获取当前对象的列映射
        mapper = inspect(self).mapper
        # 生成字段字典
        return {col.key: getattr(self, col.key) for col in mapper.columns}

使用时直接调用方法即可:

query.update(new_setting.to_dict())

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 07:22:49