覆盖 Pydantic 中子类的字段别名
override field alias from subclass in 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']}
我怎样才能做到这一点?
你不需要子类化来完成你想要的(除非你的需要比你的例子更复杂)。
对于导入: 将 Config
选项添加到 allow_population_by_field_name
以便您可以使用 names
或 firstnames
添加数据
导出:在dict()
方法中添加by_alias=True
控制输出
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']}
我有 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']}
我怎样才能做到这一点?
你不需要子类化来完成你想要的(除非你的需要比你的例子更复杂)。
对于导入: 将 Config
选项添加到 allow_population_by_field_name
以便您可以使用 names
或 firstnames
添加数据
导出:在dict()
方法中添加by_alias=True
控制输出
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']}