introduction
In Pydantic, you can use it in addition tofield_validator
In addition to verifying a single field, the decorator can also use itmodel_validator
The decorator verifies the entire model.model_validator
Allows you to perform additional validation of the entire model's data after field-level validation. In this tutorial, we will explore how to usemodel_validator
Decorators 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:a
andb
。
from pydantic import BaseModel class Model(BaseModel): a: str b: int
Use model_validator decorator
model_validator
The decorator allows you to add custom verification logic to the model. To use it, follow these steps:
Importmodel_validator
: frompydantic
Importmodel_validator
。
from pydantic import BaseModel, model_validator
Define verification functions: Create a class method that accepts a parameter (the model'sdict
represents) 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_b
verification function, it checksa
Does the value of the field contain a substring?" foobar "
,as well asb
Whether the value of the field is at least 10.
3. Application Decorators: use@model_validator
Syntax 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 becausea
The value of the field contains" foobar "
Andb
The value of the field is at least 10. The second instance failed to create becausea
The value of the field does not contain" foobar "
, andb
The value of the field is less than 10, so it is thrownValidationError
。
Advanced Usage
model_validator
The decorator also supports some advanced functions, such as:
Custom verification mode: By settingmode
Parameters, 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_fields
Parameters, 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_validator
simplified 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_validator
The function defines a decorator that accepts two optional keyword parameters:mode
andcheck_fields
。
Internal functionsdec
:
-
dec
is an internal function that accepts a callable objectf
As a parameter and return a_decorators.PydanticDescriptorProxy
Object. - The code is checked first
f
Whether it is an instance method. If so, throwPydanticUserError
,becausemodel_validator
Cannot be applied to instance methods. - Then, make sure
f
It is a class method. - Create a pattern and field check flag
_decorators.ModelValidatorDecoratorInfo
Object. - Finally, return one
_decorators.PydanticDescriptorProxy
Object, it wraps the original functionf
and model verification information.
returndec
:
model_validator
Function returnsdec
function, it will be applied as a decorator to the verification function.
in conclusion
In this tutorial, we learned how to use Pydantic'smodel_validator
Decorator 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!