You can make optional fields required in subclasses, but you cannot make required fields optional in subclasses. In fastapi author tiangolo's boilerplate projects, he utilizes a pattern like this for your example:
class ParentBase(BaseModel):
"""Shared properties."""
name: str
email: str
class ParentCreate(ParentBase):
"""Properties to receive on item creation."""
# dont need id here if your db autocreates it
pass
class ParentUpdate(ParentBase):
"""Properties to receive on item update."""
# dont need id as you are likely PUTing to /parents/{id}
# other fields should not be optional in a PUT
# maybe what you are wanting is a PATCH schema?
pass
class ParentInDBBase(ParentBase):
"""Properties shared by models stored in DB - !exposed in create/update."""
# primary key exists in db, but not in base/create/update
id: int
class Parent(ParentInDBBase):
"""Properties to return to client."""
# optionally include things like relationships returned to consumer
# related_things: List[Thing]
pass
class ParentInDB(ParentInDBBase):
"""Additional properties stored in DB."""
# could be secure things like passwords?
pass
Yes, I agree this is incredibly verbose and I wish it wasn't. You still likely end up with other schemas more specific to particular forms in your UI. Obviously, you can remove some of these as they aren't necessary in this example, but depending on other fields in your DB, they may be needed, or you may need to set defaults, validation, etc.
In my experience for validators, you have to re-declare them but you can use a shared function, ie:
def clean_article_url(cls, v):
return clean_context_url(v.strip())
class MyModel(BaseModel):
article_url: str
_clean_url = pydantic.validator("article_url", allow_reuse=True)(clean_article_url)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…