Reputation: 76
Is it possible to just execute a validator for a certain value?
Let's say I have the following case, where I have a class with two boolean fields and I use a validator to make sure that field1
can't be True when field2
is set to True:
from pydantic import BaseModel, validator
class MyClass(BaseModel):
field1: bool
field2: bool
@validator('field2')
def both_fields_are_true(cls, v, values):
field1 = values.get('field1')
if field1 and field2:
raise ValueError
return v
myClass = MyClass(field1=True, field2=False)
The instance myClass
will run the validator, but it is not needed as the second field is set to False, and then, the validation does not make sense anymore.
How can I avoid my class from executing the validation in such a case like that? I know the result will be the same anyway, but it is good to avoid executing things when they're not needed.
Upvotes: 1
Views: 527
Reputation: 11346
You can use @root_validator, which is performed on the entire model's data:
class MyClass(BaseModel):
field1: bool
field2: bool
@root_validator
def both_fields_are_true(cls, values):
field1, field2 = values.get('field1'), values.get('field2')
if field1 and field2:
raise ValueError('Both fields are true')
return values
myClass = MyClass(field1=True, field2=False)
Upvotes: 1