101591 Views
79842 Views
45596 Views
44332 Views
40991 Views
33419 Views
Raspberry Pi Time machine
Now Ad-Free
Guiding Light
Sync Files on your Pis, with Syncthing
NextCloud
Buddy Jr.
Introduction to FreeCAD for Beginners
Building a Robot Arm with Raspberry Pi and PCA9685
Building User Authentication for Static Sites with FastAPI
Mastering Pydantic for Robust Data Validation
Mastering Markdown for Documentation with Jekyll
Introduction to Rust
KevsRobots Learning Platform
32% Percent Complete
By Kevin McAleer, 2 Minutes
While type annotations and basic validators cover many common use cases, Pydantic also allows for custom validation logic through the use of decorators. This enables you to define your own rules for data validation, transformation, and normalization.
validator
Pydantic’s validator decorator allows you to attach custom validation functions to model fields. These functions can perform additional checks and transformations on field values.
from pydantic import BaseModel, field_validator, ValidationInfo class Product(BaseModel): name: str description: str price: float discount_price: float @field_validator('discount_price') def check_discount_price(cls, v: str, info: ValidationInfo): if 'price' in info.data and v >= info.data['price']: raise ValueError('discount_price must be less than the price') return v
In this example, a Product model is defined with a custom validator for the discount_price field. The validator ensures that the discount_price is always less than the price.
Product
discount_price
price
Validators can be set to run either before (pre=True) or after Pydantic’s standard validation. Pre-validators are useful for data transformation or normalization, while post-validators can enforce additional constraints on validated data.
pre=True
@validator('signup_ts', pre=True) def parse_signup_ts(cls, v): # Example pre-validator to parse a string into a datetime return parse_date_string(v)
Validators are not limited to simple conditions. They can incorporate complex logic, accessing other fields in the model via the values argument, and can even raise multiple errors.
values
Validators can be shared between models or fields by defining them as standalone functions and using the each_item=True parameter for iterable fields.
each_item=True
Create a User model with fields for username, email, and age. Implement custom validators that:
User
username
email
age
@
Experiment with both pre and post validators to familiarize yourself with their differences and applications.
< Previous Next >