gpt4 book ai didi

python - 如何扩展pydantic对象并更改某些字段的类型?

转载 作者:行者123 更新时间:2023-12-03 21:13:41 27 4
gpt4 key购买 nike

有两个类似的 pydantic 对象。唯一的区别是某些字段是可选的。
如何只定义一个对象中的字段并扩展到另一个对象?

class ProjectCreateObject(BaseModel):
project_id: str
project_name: str
project_type: ProjectTypeEnum
depot: str
system: str
...

class ProjectPatchObject(ProjectCreateObject):
project_id: str
project_name: Optional[str]
project_type: Optional[ProjectTypeEnum]
depot: Optional[str]
system: Optional[str]
...

最佳答案

我通过 __init__subclass__ 找到了一个简单又好用的方法.
文档也可以成功生成。

class ProjectCreateObject(BaseModel):
project_id: str
project_name: str
project_type: ProjectTypeEnum
depot: str
system: str
...

def __init_subclass__(cls, optional_fields=None, **kwargs):
"""
allow some fields of subclass turn into optional
"""
super().__init_subclass__(**kwargs)
if optional_fields:
for field in optional_fields:
cls.__fields__[field].outer_type_ = Optional
cls.__fields__[field].required = False

_patch_fields = ProjectCreateObject.__fields__.keys() - {'project_id'}

class ProjectPatchObject(ProjectCreateObject, optional_fields=_patch_fields):
pass

关于python - 如何扩展pydantic对象并更改某些字段的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61948723/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com