python - 覆盖 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
对于导出:添加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']}
推荐阅读
- arcgis - 使用 ArcGIS API for JavaScript 时如何使用外部数据
- java - 如何压缩数组的原始整数数据?
- audio - Aframe 音频资产 - 正确断开音频源
- javascript - 无法用 Array.length 计算
- android - 使用 BroadcastReceiver 传递 Intent.EXTRAS
- php - 如何防止主 Laravel 表单提交?
- javascript - google-apps 脚本 - 循环
- python-3.x - 安装 Scrapy 后 Python 3.7 崩溃
- android - Camera2 三星 Galaxy s9 预览尺寸
- kubernetes - 完整 Kubernetes emptyDIr 的终止宽限期?