我用Student模型撰寫了一些 API ,用于更新它 - 我使用另一個模型StudentUpdateIn。在Student模型上我有驗證器( gt = 15 )。但是我如何也可以應用這個驗證器StudentUpdateIn呢?
我找到了 using 的方法@validator,但我認為這不是我應該在代碼中使用的方法。
原來是選擇不正確的模式....
class StudentUpdateIn(BaseModel):
first_name: Optional[str]
last_name: Optional[str]
age: Optional[int]
group: Optional[str]
@validator('age')
def greater_than(cls, v):
if not v > 15:
raise ValueError("Age must be greater than 15")
class StudentIn(BaseModel):
first_name: str = Field(..., max_length=30)
last_name: str = Field(..., max_length=30)
age: int = Field(..., gt=15)
group: str = Field(..., max_length=10)
uj5u.com熱心網友回復:
我很確定沒有非 hacky 的方法,但是如果您不介意在代碼中進行一些自省,這里是裝飾器,它采用欄位名稱并在內部將 pydantic 欄位標記為不需要(可選):
import inspect
def optional(*fields):
def dec(_cls):
for field in fields:
_cls.__fields__[field].required = False
return _cls
if fields and inspect.isclass(fields[0]) and issubclass(fields[0], BaseModel):
cls = fields[0]
fields = cls.__fields__
return dec(cls)
return dec
現在您可以使用它并擁有單個類:
# you can specify optional fields - @optional("age", "group")
@optional
class StudentIn(BaseModel):
first_name: str = Field(..., max_length=30)
last_name: str = Field(..., max_length=30)
age: int = Field(..., gt=15)
group: str = Field(..., max_length=10)
或繼承
@optional
class StudentUpdateIn(StudentIn):
...
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/358781.html
