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

Pydantic自定义序列化转驼峰时如何包含computed_field?

问题:Pydantic自定义序列化器未包含计算字段

你遇到的核心问题是:遍历self的方式只能获取模型的常规字段,计算字段(Computed Field)不会被包含在这个迭代中,所以最终序列化结果里看不到bippity_boink。

解决方案1:调用默认model_dump()获取所有字段

直接利用Pydantic内置的序列化逻辑拿到包含计算字段的完整结果,再统一转换键为驼峰格式,这是最简洁的方式:

import pydantic

class SuperSickClass(pydantic.BaseModel):
    bing_bong: int

    @pydantic.computed_field
    @property
    def bippity_boink(self) -> int:
        return self.bing_bong + 1

    @pydantic.model_serializer
    def ser_model(self):
        # 获取默认序列化结果,包含所有字段(常规+计算)
        default_output = self.model_dump()
        camel_case_output = {}
        for key, value in default_output.items():
            # 下划线转驼峰
            camel_key = ''.join(word.capitalize() for word in key.split('_'))
            camel_case_output[camel_key] = value
        return camel_case_output

if __name__ == '__main__':
    super_sick_instance = SuperSickClass(bing_bong=1)
    print(super_sick_instance.model_dump())
    # 输出: {'BingBong': 1, 'BippityBoink': 2}

解决方案2:手动遍历常规字段+计算字段

如果需要更精细的控制,可以分别遍历model_fields(常规字段)和model_computed_fields(计算字段),手动收集值并转换格式:

import pydantic

class SuperSickClass(pydantic.BaseModel):
    bing_bong: int

    @pydantic.computed_field
    @property
    def bippity_boink(self) -> int:
        return self.bing_bong + 1

    @pydantic.model_serializer
    def ser_model(self):
        camel_case_output = {}
        # 处理常规字段
        for field_name in self.model_fields:
            camel_key = ''.join(word.capitalize() for word in field_name.split('_'))
            camel_case_output[camel_key] = getattr(self, field_name)
        # 处理计算字段
        for field_name in self.model_computed_fields:
            camel_key = ''.join(word.capitalize() for word in field_name.split('_'))
            camel_case_output[camel_key] = getattr(self, field_name)
        return camel_case_output

if __name__ == '__main__':
    super_sick_instance = SuperSickClass(bing_bong=1)
    print(super_sick_instance.model_dump())
    # 输出: {'BingBong': 1, 'BippityBoink': 2}

原代码不生效的原因

原代码中for field_name, field_value in self:的遍历方式,只会迭代Pydantic模型的常规字段(即类顶部定义的bing_bong这类字段)。而计算字段是通过@property和@computed_field装饰的属性,不属于常规字段的迭代范围,因此不会被加入到输出字典中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 14:53:09