从Pydantic中的子类重写字段别名

2024-06-25 23:11:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个模型,一个是另一个的子类:

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']}

我怎样才能做到这一点


Tags: fromimportdatanamesdictlistclassbasemodel
1条回答
网友
1楼 · 发布于 2024-06-25 23:11:43

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

对于导入:Config选项添加到allow_population_by_field_name,以便可以使用namesfirstnames添加数据

用于导出:by_alias=True添加到dict()方法以控制输出

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']}

相关问题 更多 >