你可以通过编写setter方法来实现一个解决方案。
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
def set_a_and_b(self, value):
self.Config.validate_assignment = False
self.a, self.b = value, value
self.Config.validate_assignment = True
PoC:
>>> example = Example(a=1, b=1)
>>> example.a = 2
Traceback (most recent call last):
File "D:\temp\venv\lib\site-packages\IPython\core\interactiveshell.py", line 3398, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-4-950b5db07c46>", line 1, in <cell line: 1>
example.a =2
File "pydantic\main.py", line 393, in pydantic.main.BaseModel.__setattr__
pydantic.error_wrappers.ValidationError: 1 validation error for Example
__root__
a and b must be equal (type=value_error)
>>> example.set_a_and_b(2)
>>> example
Example(a=2, b=2)
>>> example.a = 3
Traceback (most recent call last):
File "D:\temp\venv\lib\site-packages\IPython\core\interactiveshell.py", line 3398, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-8-d93e8eb8a0e3>", line 1, in <cell line: 1>
example.a = 3
File "pydantic\main.py", line 393, in pydantic.main.BaseModel.__setattr__
pydantic.error_wrappers.ValidationError: 1 validation error for Example
__root__
a and b must be equal (type=value_error)
但也许在您的实际情况中,您应该使用一些setter和getter方法来代替(或与)标准验证一起使用。