你自己已经回答得差不多了。除非问题还有更多。
from typing import Optional
from pydantic import BaseModel
class ProjectCreateObject(BaseModel):
project_id: str
project_name: str
project_type: str
depot: str
system: str
class ProjectPatchObject(ProjectCreateObject):
project_name: Optional[str]
project_type: Optional[str]
depot: Optional[str]
system: Optional[str]
if __name__ == "__main__":
p = ProjectCreateObject(
project_id="id",
project_name="name",
project_type="type",
depot="depot",
system="system",
)
print(p)
c = ProjectPatchObject(project_id="id", depot="newdepot")
print(c)
运行这个给出:
project_id='id' project_name='name' project_type='type' depot='depot' system='system'
project_id='id' project_name=None project_type=None depot='newdepot' system=None
另一种看待它的方法是将基础定义为可选,然后创建一个验证器来检查何时都需要:
from pydantic import BaseModel, root_validator, MissingError
class ProjectPatchObject(BaseModel):
project_id: str
project_name: Optional[str]
project_type: Optional[str]
depot: Optional[str]
system: Optional[str]
class ProjectCreateObject(ProjectPatchObject):
@root_validator
def check(cls, values):
for k, v in values.items():
if v is None:
raise MissingError()
return values