从API数据初始化时,在Pydantic中传递一个额外的值给类



使用Pydantic非常新,但我目前正在将从API返回的json传递给Pydantic类,它很好地将json解码为类,而无需我做任何事情。

然而,我现在想在初始化时从父类传递一个额外的值给子类,但我不知道怎么做。

在下面的例子中,我想把父类的id传递给子类。

从api返回的数据示例
{
"id": "162172481",
"filed_at": "2022-11-12",
"child": {
"items": ["item1", "item2", "item3"]   
}
}

pydantic类

class ExampleA(BaseModel):
class ChildA(BaseModel):
parent_id: str # how do I pass this in
items: list[str]
id: str
filed_at: date = Field(alias="filedAt")
child: ChildA
class Config:
allow_population_by_field_name = True

初始化数据

data = API.get_example_data()
example_class = ExampleA(**data)

我认为没有办法自己做这件事。但是我认为最优雅的方法是使用验证器。

class ExampleA(BaseModel):
class ChildA(BaseModel):
parent_id: str  # how do I pass this in
items: list[str]
id: str
filed_at: date = Field(alias="filedAt")
child: ChildA
@validator('child', pre=True)
def inject_id(cls, v, values):
v['parent_id'] = values['id']
return v
class Config:
allow_population_by_field_name = True

重要的部分是pre=True,以便在child初始化之前运行验证器。

最新更新