How do you update multiple properties on a pydantic model that are validated together and dependent upon each other?
Here is a contrived but simple example:
from pydantic import BaseModel, root_validator
class Example(BaseModel):
a: int
b: int
@root_validator
def test(cls, values):
if values['a'] != values['b']:
raise ValueError('a and b must be equal')
return values
class Config:
validate_assignment = True
example = Example(a=1, b=1)
example.a = 2 # <-- error raised here because a is 2 and b is still 1
example.b = 2 # <-- don't get a chance to do this
Error:
ValidationError: 1 validation error for Example
__root__
a and b must be equal (type=value_error)
Both a
and b
having a value of 2
is valid, but they can't be updated one at a time without triggering the validation error.
Is there a way to put the validation on hold until both are set? Or a way to somehow update both of them at the same time? Thanks!