I have a nested model in Pydantic. I have a root_validator function in the outer model. I was under the impression that if the outer root validator is called, then the inner model is valid. But apparently not. In the following MWE, I give the wrong field name to the inner model, but the outer validator is failing:
from typing import List
from pydantic import BaseModel
from pydantic.class_validators import root_validator
class CarList(BaseModel):
cars: List[str]
colors: List[str]
class CarDealership(BaseModel):
name: str
cars: CarList
@root_validator()
def check_length(cls, v):
cars_list = v.get("cars")
if len(cars_list.cars) != len(cars_list.colors):
raise ValueError("wrong length")
return v
car_deal = {
"cars": {
"cars1": ["toyota", "tesla"],
"colors": ["white", "red"]
}
}
CarDealership.parse_obj(car_deal)
The error I get is:
File "test.py", line 17, in check_length
if len(cars_list.cars) != len(cars_list.colors):
AttributeError: 'NoneType' object has no attribute 'cars'
I was expecting something like:
pydantic.error_wrappers.ValidationError: 1 validation error for CarList
cars
field required (type=value_error.missing)
How can I make sure the inner model is validated first?