I'm using the pydantic BaseModel
with a validator like this:
from datetime import date
from typing import List, Optional
from pydantic import BaseModel, BaseConfig, validator
class Model(BaseModel):
class Config(BaseConfig):
allow_population_by_alias = True
fields = {
"some_date": {
"alias": "some_list"
}
}
some_date: Optional[date]
some_list: List[date]
@validator("some_date", pre=True, always=True)
def validate_date(cls, value):
if len(value) < 2: # here value is some_list
return None
return value[0] # return the first value - let's assume it's a date string
# This reproduces the problem
m = Model(some_list=['2019-01-03'])
I would like to compute the value of some_date
based on the value of some_list
and make it None
if a certain condition met.
My JSON never contains the field some_date
, it's always populated based on some_list
hence pre=True, always=True
. However the default validator for some_date
will run after my custom one, which will fail if validate_date
returns None
.
Is there a way to create such a field which is only computed by another one and still can be Optional
?