1

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 :)

Da sil
  • 52
  • 7
  • Please have a look at [this answer](https://stackoverflow.com/a/71258131/17865804) and [this answer](https://stackoverflow.com/a/72003724/17865804) – Chris Mar 06 '23 at 06:57

1 Answers1

2

You need to change the order of fields so startFrom comes after startTo, review the docs on order of fields.

SColvin
  • 11,584
  • 6
  • 57
  • 71