I'm trying to use pydantic for a fastapi app to restrict the provided date to be less than today. From the pydantic docs I see a nice function condate
, which has a lt
argument - that's exactly what I need.
My code is:
from datetime import date
from pydantic import BaseModel, condate
class RiskData(BaseModel):
dob: condate(lt=date.today())
which provides the following error:
File "pydantic\main.py", line 342, in pydantic.main.BaseModel.__init__
pydantic.error_wrappers.ValidationError: 2 validation errors for OpenAPI
components -> schemas -> RiskData -> properties -> dob -> exclusiveMaximum
value is not a valid float (type=type_error.float)
components -> schemas -> RiskData -> $ref
field required (type=value_error.missing)
I know that I can use pydantic.validator
to achive the functionality that I need, but maybe pydantic allows me to save a couple of lines.
CodePudding user response:
It looks like generating OpenApi Schema by FastAPI does not support Type: condate.
You'd better change to this,
from datetime import date
from pydantic import BaseModel, validator
class RiskData(BaseModel):
dob: date
@validator("dob")
def validate_dob(cls, v, values, **kwargs):
if v < date.today():
raise ValueError("Your Error Message")
return v