首页 > 解决方案 > 覆盖 Pydantic 中子类的字段别名

问题描述

我有 2 个模型,1 个子类化另一个:

from pydantic import BaseModel
from typing import List

class Model1(BaseModel):
    names: List[str]

class Model2(Model1):
    # define here an alias for names -> e.g. "firstnames"
    pass

data = { "names": ["rodrigo", "julien", "matthew", "bob"] }
# Model1(**data).dict()  -> gives {'names': ['rodrigo', 'julien', 'matthew', 'bob']}
# Model2(**data).dict()  -> gives {'firstnames':  ['rodrigo', 'julien', 'matthew', 'bob']}

我怎样才能做到这一点?

标签: pythonpydantic

解决方案


你不需要子类来完成你想要的(除非你的需要比你的例子更复杂)。

对于导入:添加Config选项,allow_population_by_field_name以便您可以使用names或添加数据firstnames

对于导出:添加by_alias=Truedict()方法来控制输出

from pydantic import BaseModel
from typing import List


class Model(BaseModel):
    names: List[str] = Field(alias="firstnames")

    class Config:
        allow_population_by_field_name = True


def main():
    data = {"names": ["rodrigo", "julien", "matthew", "bob"]}
    model = Model(**data)
    print(model.dict())
    print(model.dict(by_alias=True))


if __name__ == '__main__':
    main()

产量:

{'names': ['rodrigo', 'julien', 'matthew', 'bob']}
{'firstnames': ['rodrigo', 'julien', 'matthew', 'bob']}

推荐阅读