如何在Pydantic的TypeAdapter验证时临时为缺失字段设默认值?
在Pydantic中临时为缺失字段设置默认值的解决方案
可以实现需求,无需修改原Thing类定义,仅针对本次数据验证生效。最直接的方式是创建临时子类并添加前置验证器,在数据进入模型验证前补全缺失字段的默认值,具体实现如下:
import pydantic from typing import Any class Thing(pydantic.BaseModel): one: int two: str three: bool # 定义临时子类,仅用于本次验证,不修改原Thing类 class TempThing(Thing): @pydantic.model_validator(mode='before') @classmethod def fill_default_three(cls, data: Any) -> Any: # 仅当字典中缺失three字段时,补充默认值True if isinstance(data, dict) and 'three' not in data: data['three'] = True return data # 使用临时子类创建TypeAdapter adapter = pydantic.TypeAdapter(dict[str, TempThing]) raw_data = {"this": {"one": 1, "two": "zwei"}, "that": {"one": 111, "two": "dos"}} # 验证数据,自动补全three字段的默认值 things_i_want = adapter.validate_python(raw_data) print(things_i_want) # 输出结果: # {'this': TempThing(one=1, two='zwei', three=True), 'that': TempThing(one=111, two='dos', three=True)}
方案说明
- 临时子类
TempThing继承自原Thing类,仅添加了一个前置验证器,不改变原类的任何定义; model_validator(mode='before')会在数据进入模型字段验证前执行,检查并补全缺失的three字段;- 验证完成后得到的对象本质上是
TempThing实例,若需要转换为原Thing类型,可通过Thing(**obj.model_dump())完成。
内容的提问来源于stack exchange,提问作者Ray
相关产品推荐
相关产品推荐

