from pydantic import BaseModel, validator
def validator_decorator(message):
def decorator(func):
def wrapper(cls, v, values, config, field):
# Call the original validator function
result = func(cls, v, values, config, field)
# Print the message after the validator runs
print(message)
return result
return wrapper
return decorator
class MyModel(BaseModel):
name: str
@validator_decorator("name validator")
@validator('name')
def name_must_contain_space(cls, v):
if ' ' not in v:
raise ValueError('must contain a space')
return v.title()
Testing the model
try:
MyModel(name=”John”)
except ValueError as e:
print(e)
model = MyModel(name=”John Doe”)
print(model.name)
that validator decorator is not working as expected and not printing any messages , help me how to write the wrapper to run the validator processed function
Kuruva Vinod Kumar is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
You can do something like the following:
from typing import Callable, Type
from pydantic.v1 import BaseModel, validator
def validator_decorator(field: str, message: str) -> Callable:
def decorator(func: Callable) -> Callable:
@validator(field)
def wrapper(cls: Type[BaseModel], value: str) -> str:
result = func(cls, value)
print(message)
return result
return wrapper
return decorator
class MyModel(BaseModel):
name: str
@validator_decorator(field="name", message="name validator")
def name_must_contain_space(cls, value: str) -> str:
if " " not in value:
raise ValueError("Value mast contain space.")
return value.title()