Reputation: 143
I'm trying to validate some field according to other fields, example:
from pydantic import BaseModel, validator
class MyClass(BaseModel):
type: str
field1: Optional[str] = None
field2: Optional[str] = None
field3: Optional[str] = None
@validator("type")
def has_required_fields(cls, v, values):
required_fields = {"v1": ["field1", "field3"], "v2": ["field2"]}
for required_field in required_fields[c]:
if not values[required_field]:
raise Exception
But my issue is that the values dict is empty. How should I access the other fields correctly in this situation?
Upvotes: 2
Views: 5775
Reputation: 143
Fields are validated in order they are initialized. Dictionary is empty because there is no validated fields as the type is the first field to be validated.
-> Reorder the field initialization or -> Use root validator
Upvotes: 3
Reputation: 554
I believe you need to set “always=True” in the validator if you plan on type being empty when you initialize it. See here:
https://github.com/pydantic/pydantic/issues/691#issuecomment-785101470
Upvotes: 0