如何根据已解析字典中的值更改 pydantic 解析的类型?

时间:2021-06-25 08:58:41

标签: pydantic

我希望 pydantic 选择用于根据输入值解析输入的模型。这可能吗?

MVCE

我有一个与此类似的 pydantic 模型:

from typing import List, Literal
from pydantic import BaseModel


class Animal(BaseModel):
    name: str
    type: Literal["mamal", "bird"]


class Bird(Animal):
    max_eggs: int


class Mamal(Animal):
    max_offspring: int


class Config(BaseModel):
    animals: List[Animal]


cfg = Config.parse_obj(
    {
        "animals": [
            {"name": "eagle", "type": "bird", "max_eggs": 3},
            {"name": "Human", "type": "mamal", "max_offspring": 3},
        ]
    }
)

print(cfg.json(indent=4))

给予

{
    "animals": [
        {
            "name": "eagle",
            "type": "bird"
         <-- missing max_offspring, as "Animal" was used instead of Bird
        },
        {
            "name": "Human",
            "type": "mamal"
          <-- missing max_offspring, as "Animal" was used instead of Mamal
        }
    ]
}

我知道我可以在 Config.extra="allow" 中设置 Animal,但这不是我想要的。我希望 pydantic 看到带有 'type': 'mamal' 的字典应该使用 Mamal 模型进行解析。

这可能吗?

1 个答案:

答案 0 :(得分:1)

您可以向每个子类添加具体的文字,以区分它们并将它们放在 Union 中,从更具体到不太具体的顺序。像这样:

class Animal(BaseModel):
    name: str
    type: str


class Bird(Animal):
    type: Literal["bird"]
    max_eggs: int


class Mamal(Animal):
    type: Literal["mamal"]
    max_offspring: int

class Config(BaseModel):
    animals: List[Union[Bird, Mamal, Animal]]  # From more specific to less
相关问题