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

如何使用Pydantic(v1.10)模型方法导出模型property属性?

能否通过Pydantic v1.10的模型方法导出property属性?

默认情况下,Pydantic v1.10的dict()方法不会导出模型的property属性——该方法仅序列化模型中显式定义的字段(比如示例中的a: int),而property不属于模型的字段集合。

要实现将property属性包含在dict()的输出中,有两种常用方案:

方案1:重写模型的dict()方法

直接在模型中重写dict()方法,在父类序列化结果的基础上手动添加property的值:

from pydantic import BaseModel

class Foo(BaseModel):
    a: int 

    @property
    def square(self):
        return self.a ** 2  # 修正:需通过self访问实例属性a

    def dict(self, **kwargs):
        # 先调用父类的dict()获取基础字段数据
        base_data = super().dict(**kwargs)
        # 添加property属性到结果中
        base_data["square"] = self.square
        return base_data

foo = Foo(a=2)
assert "square" in foo.dict()  
assert foo.dict()["square"] == foo.dict()["a"] ** 2

方案2:将property转为计算字段(通过validator)

如果可以接受将square转为模型的显式字段,可使用@validator装饰器创建一个始终自动计算的字段:

from pydantic import BaseModel, validator

class Foo(BaseModel):
    a: int
    square: int  # 显式定义字段

    @validator("square", always=True)
    def compute_square(cls, _, values):
        # values包含已验证的其他字段值
        return values["a"] ** 2

foo = Foo(a=2)
assert "square" in foo.dict()  
assert foo.dict()["square"] == 4

注意:方案2中square会被视为模型的正式字段,初始化时无需传入(always=True会强制计算),但序列化时会被包含在结果里。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 14:52:17