Skip to content
Advertisement

How to reuse a root_validator in Pydantic?

The Pydantic docs have an example of reusing a validator:
https://pydantic-docs.helpmanual.io/usage/validators/#reuse-validators

Is it possible to reuse a root validator?

Advertisement

Answer

Yes, it is possible and the API is very similiar

Example:

from datetime import datetime

from pydantic import BaseModel, validator
from pydantic.class_validators import root_validator

def validate_start_time_before_end_time(cls, values):
    """
    Reusable validator for pydantic models
    """
    if values["start_time"] >= values["end_time"]:
        raise ValueError("start_time must be before end_time")
    return values

class Model1(BaseModel):
    start_time: datetime
    end_time: datetime

    # validators
    _datetime_order_validation = root_validator(allow_reuse=True)(
        validate_start_time_before_end_time
    )

class Model2(BaseModel):
    start_time: datetime
    end_time: datetime

    # validators
    _datetime_order_validation = root_validator(allow_reuse=True)(
        validate_start_time_before_end_time
    )

It is also possible to parameterize the validator like in this example https://github.com/samuelcolvin/pydantic/discussions/2938

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement