如何在初始化Pydantic类时从父类向子类传递额外值?
解决Pydantic父类ID传递给子类字段的问题
这里有几种实用的方法可以实现将父类ExampleA的id传递给子类ChildA的parent_id字段:
方法1:使用模型验证器(推荐)
利用Pydantic的验证器在模型实例化完成后自动赋值,不同版本写法略有区别:
Pydantic v2版本
from pydantic import BaseModel, Field, model_validator from datetime import date class ExampleA(BaseModel): class ChildA(BaseModel): parent_id: str items: list[str] id: str filed_at: date = Field(alias="filedAt") child: ChildA class Config: allow_population_by_field_name = True @model_validator(mode='after') def set_child_parent_id(self): self.child.parent_id = self.id return self
Pydantic v1版本
from pydantic import BaseModel, Field, root_validator from datetime import date class ExampleA(BaseModel): class ChildA(BaseModel): parent_id: str items: list[str] id: str filed_at: date = Field(alias="filedAt") child: ChildA class Config: allow_population_by_field_name = True @root_validator(skip_on_failure=True) def set_child_parent_id(cls, values): child = values.get('child') if child and 'id' in values: child.parent_id = values['id'] return values
这种方法会在模型验证通过后自动完成赋值,不需要额外修改输入数据或手动操作。
方法2:提前修改输入数据
在实例化ExampleA之前,直接把父ID添加到child的字典中:
data = API.get_example_data() # 给child字典添加parent_id字段 data['child']['parent_id'] = data['id'] example_class = ExampleA(**data)
这种方法简单直接,适合不需要复杂逻辑的场景。
方法3:实例化后手动赋值
实例化完成后,直接给子类字段赋值:
data = API.get_example_data() example_class = ExampleA(**data) example_class.child.parent_id = example_class.id
这种方法最直观,适合快速调试或简单场景。
内容的提问来源于stack exchange,提问作者connorvo
相关产品推荐
相关产品推荐

