108271 Views
83628 Views
56847 Views
48511 Views
47826 Views
47705 Views
Arduino Plug and Make Kit Review
Pi to Pico W Bluetooth Communication
Two-Way Bluetooth Communication Between Raspberry Pi Picos
Gamepad 2
Picotamachibi 2
Learning System updates
Introduction to the Linux Command Line on Raspberry Pi OS
How to install MicroPython
Wall Drawing Robot Tutorial
BrachioGraph Tutorial
Intermediate level MicroPython
Introduction to FreeCAD for Beginners
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 >