SoFunction
Updated on 2025-04-14

Implementation of model_validator in Pydantic

introduction

In Pydantic, you can use it in addition tofield_validatorIn addition to verifying a single field, the decorator can also use itmodel_validatorThe decorator verifies the entire model.model_validatorAllows you to perform additional validation of the entire model's data after field-level validation. In this tutorial, we will explore how to usemodel_validatorDecorators to create custom model verification logic.

Basic knowledge

Before you start, make sure you have Pydantic installed. If not, please install it with the following command:

pip install pydantic

Create a Pydantic model

First, let's create a simple Pydantic model. This model will contain two fields:aandb

from pydantic import BaseModel
class Model(BaseModel):
    a: str
    b: int

Use model_validator decorator

model_validatorThe decorator allows you to add custom verification logic to the model. To use it, follow these steps:

Importmodel_validator: frompydanticImportmodel_validator

from pydantic import BaseModel, model_validator

Define verification functions: Create a class method that accepts a parameter (the model'sdictrepresents) and returns the validated model.

class Model(BaseModel):
    a: str
    b: int
    @model_validator
    @classmethod
    def check_a_and_b(cls, values: dict):
        if values['a'] != ' foobar ':
            raise ValueError('Field "a" must contain " foobar "')
        if values['b'] < 10:
            raise ValueError('Field "b" must be at least 10')
        return cls(**values)

In this example, we define a name calledcheck_a_and_bverification function, it checksaDoes the value of the field contain a substring?" foobar ",as well asbWhether the value of the field is at least 10.

3. Application Decorators: use@model_validatorSyntax applies the decorator to the verification function.

4. Test the model: Create a model instance and test the verification logic.

# Correct valuemodel = Model(a=' foobar ', b=20)
print(model)
# Error valuetry:
    model = Model(a='snap', b=5)
except ValidationError as exc_info:
    print(exc_info)

In the example above, the first model instance was successfully created becauseaThe value of the field contains" foobar "AndbThe value of the field is at least 10. The second instance failed to create becauseaThe value of the field does not contain" foobar ", andbThe value of the field is less than 10, so it is thrownValidationError

Advanced Usage

model_validatorThe decorator also supports some advanced functions, such as:

Custom verification mode: By settingmodeParameters, you can specify whether the verification is performed before or after the field verification.

@model_validator(mode='before')

Check the existence of fields: By settingcheck_fieldsParameters, which can control whether checking whether the field actually exists in the model.

@model_validator(check_fields=False)

model_validator decorator source code

The following ismodel_validatorsimplified version of the decorator source code:

def model_validator(mode: ModelValidatorModes = 'after', check_fields: bool | None = None) -> Callable[[Any], Any]:
    def dec(f: Callable[..., Any] | staticmethod[Any, Any] | classmethod[Any, Any, Any]) -> _decorators.PydanticDescriptorProxy[Any]:
        if _decorators.is_instance_method_from_sig(f):
            raise PydanticUserError(
                '`@model_validator` cannot be applied to instance methods', code='validator-instance-method'
            )
        # auto apply the @classmethod decorator
        f = _decorators.ensure_classmethod_based_on_signature(f)
        dec_info = _decorators.ModelValidatorDecoratorInfo(mode=mode, check_fields=check_fields)
        return _decorators.PydanticDescriptorProxy(f, dec_info)
    return dec

Source code interpretation

Decorator definition:

model_validatorThe function defines a decorator that accepts two optional keyword parameters:modeandcheck_fields

Internal functionsdec:

  • decis an internal function that accepts a callable objectfAs a parameter and return a_decorators.PydanticDescriptorProxyObject.
  • The code is checked firstfWhether it is an instance method. If so, throwPydanticUserError,becausemodel_validatorCannot be applied to instance methods.
  • Then, make surefIt is a class method.
  • Create a pattern and field check flag_decorators.ModelValidatorDecoratorInfoObject.
  • Finally, return one_decorators.PydanticDescriptorProxyObject, it wraps the original functionfand model verification information.

returndec:

model_validatorFunction returnsdecfunction, it will be applied as a decorator to the verification function.

in conclusion

In this tutorial, we learned how to use Pydantic'smodel_validatorDecorator to add custom verification logic to the model. With this powerful tool, you can perform complex verification of data across the entire model, ensuring the accuracy and completeness of your data.

This is the end of this article about the implementation of model_validator in Pydantic. For more related Pydantic model_validator content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!