I'm using Pydantic and i'm trying to compare than date_from is inferior to date_to (both of these fields are optional) in my Pydantic BaseModel and return a 422 error if it's not the case.
I tried to use to method presented in the StackOverflow question: pydantic Multi-field comparison - but I didn't get any success with it, I alway got a 200 succeed.
Here's my model:
class MyModel(BaseModel):
startFrom: Optional[date] = Field(
...,
description='XXX',
example='2023-03-15',
)
StartTo: Optional[date] = Field(
...,
description='XXX',
example='2023-03-31',
)
otherData: str = Field(
...,
description='XXX',
example='XX',
)
@validator('startFrom')
def date_order(cls, startFrom, values, **kwargs):
if ('StartTo' not in values):
return startFrom
if (startFrom > values['StartTo']):
raise ValueError('startFrom must be inferior to StartTo.')
return startFrom
I don't really know what I do wrong.
Thanks to everyone for you help :)