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

    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

    user = UserModel(
        name='samuel colvin',
    ) = 'samualcolvin' # Performs validation due to validate_assignment=True
except ValidationError as e:
    1 validation error for UserModel
        must contain a space (type=value_error)

As you can see in the example above, when the attribute is changed, it triggers all the associated validators with it and raises an exception.

Leave a Reply

Your email address will not be published. Required fields are marked *