In my project, all pydantic models inherit from a custom "base model" called GeneralModel.
This enables to configure the same behavior for the entire project in one place.
Let's assume the following implementation:
from pydantic import BaseModel
class GeneralModel(BaseModel):
class Config:
use_enum_values = True
exclude_none = True
One particularly desired behavior is to perform a validation on all fields of a specific type.
Any ideas how to achieve this using my GeneralModel? Different approaches are blessed as well.
Quote from the Pydantic validators documentation:
and:
So you can write a catch-all validator and pass it the
ModleFieldinstance as an argument. Then check the type of the field and apply whatever validation you want.Very simple example:
Usage:
Output:
Note: When defining a field as for example
list[str], Pydantic internally considers the field type to bestr, but its shape to bepydantic.fields.SHAPE_LIST. Luckily,shapeis also a public attribute ofModelField. See this answer for an example, where this is important.