Define simple pydantic model
BaseModelField for validationfrom pydantic import BaseModel
class Employee(BaseModel):
employee_id: UUID = Field(default_factory=uuid4, frozen=True)
department: DepartmentDefiine a field that is:
- Random uuid4 by default
- Read only
from uuid import UUID, uuid4 employee_id: UUID = Field(default_factory=uuid4, frozen=True)
Defiine a string field that:
- has at least size 1
- has at most size 10
name: str = Field(min_length=1, max_length=10
Defiine a float field that:
- is greater than 0
- is less than 110
- doesn’t show up in string representation of an object (like password)
- can be accessed by different name
salary: float = Field(alias="compensation", gt=0, lt=110, repr=False)
dictdictFrom dict
# From Employee.model_validate(new_employee_dict) To new_employee.model_dump()
From JSON
new_employee = Employee.model_validate_json(new_employee_json) To JSON new_employee.model_dump_json()
Generate JSON schema of Employee model
Employee.model_json_schema()
How to define custom validation for a field
Use field_validator
class Employee(BaseModel):
date_of_birth: date = Field(alias="birth_date", repr=False, frozen=True)
@field_validator("date_of_birth")
@classmethod
def check_valid_age(cls, date_of_birth: date) -> date:
passHow to define custom validation that involves multiple fields
Use model_validator
class Employee(BaseModel):
# `mode="after"` - Pydantic waits until after you’ve instantiated your model to run `.check_it_benefits()`.
@model_validator(mode="after")
def check_it_benefits(self) -> Self:
passWhat is pydantic-settings
pydantic-settings to create models, similar to BaseModel, that parse and validate environment variables.pydantic-settings is BaseSettings, and it has all of the same functionalities as BaseModel.BaseSettings, the model initializer will try to read any fields not passed as keyword arguments from environment variables.BaseSettings is not case-sensitive when matching environment variables to field names.