Pydantic Trigger Validation on Model Instance Field Assignment
Pydantic validators are great! The validation is performed as soon as you instantiate your model.
But how do we perform validation on modification of a particular attribute or field of the (model) instance after its creation? When we instantiate our model, all the validators run. But when we change the value of a particular (model) instance attribute or field, no associated validation is performed by default.
The answer to this problem is the validate_assignment
config option.
from pydantic import BaseModel, ValidationError, validator
class UserModel(BaseModel):
name: str
username: str
@validator('name')
def name_must_contain_space(cls, v, values):
if ' ' not in v:
raise ValueError('must contain a space')
return v.title()
class Config:
# This is what you need!
validate_assignment = True
try:
user = UserModel(
name='samuel colvin',
username='scolvin'
)
user.name = 'samualcolvin' # Performs validation due to validate_assignment=True
print(user)
except ValidationError as e:
print(e)
"""
1 validation error for UserModel
name
must contain a space (type=value_error)
"""
As you can see in the example above, when the user.name
attribute is changed, it triggers all the associated validators with it and raises an exception.