Skip to content

Pydantic

Pydantic is a Python library primarily used for data validation and settings management using Python type hints. At its core, you define data models by creating classes that inherit from Pydantic's BaseModel. The fields in these models are defined using standard Python type annotations. This makes your code more readable, easier to understand, and integrates well with linters, IDEs, and static analysis tools.

compatible with sqlAlchemy

pydantic is compatible with sqlAlchemy

convert from sqlAlchemy to pydantic model

PydanticModel.model_validate(sqlAlchemyModelObject)

if the sqlAlchemy model has constrains and relationships, pydantic model needs to be configured with

class PydanticModel(BaseModel):
    model_config = {
        from_attributes: True,
        populate_by_name: True,
        orm_mode: True,  # this is required if the model depends on other models, eg the sqlAlchemy model has relationships
    }

    ...

Features

  1. type hinting for validation
  2. more detailed Field customization 2.data coercion: auto convert input data to declared types: if declared int, received "23", will auto convert to 23
  3. clear @validator error: when the fields are problematic
  4. JSON schema/serialization generation: auto convert from/to JSON
  5. Settings Management: define settings inherit from BaseSettings -> allows auto load values from .env / secret, make config file clean

Field

BaseSettings

@validator, @model_validator