lundi 15 novembre 2021

FastAPI Optional validator

I write some API with Student model, for update it - I use another model StudentUpdateIn. On Student model I have validator ( gt = 15 ). But how I can apply this validator to StudentUpdateIn too?

I found way with using @validator, but I think it is not the way, that I should use on my code.

Originally was chosen incorrect pattern....

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)



Aucun commentaire:

Enregistrer un commentaire