pydantic-dev

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Pydantic Professional Development

Pydantic 专业开发指南

Comprehensive guidance for building production-ready applications with Pydantic v2.12, the most widely used data validation library for Python.
本指南提供使用Python最常用的数据验证库Pydantic v2.12构建生产级应用的全面指导。

Quick Reference

快速参考

Installation: See
references/install.md
for setup instructions and optional dependencies
Core Philosophy: See
references/why.md
for Pydantic's design principles and when to use it
Migration from v1: See
references/migration.md
for upgrading from Pydantic v1.x
安装说明: 详见
references/install.md
获取安装步骤及可选依赖配置
核心设计理念: 详见
references/why.md
了解Pydantic的设计原则及适用场景
从v1版本迁移: 详见
references/migration.md
获取从Pydantic v1.x升级的指南

Core Concepts

核心概念

Pydantic uses Python type hints to define data schemas and performs validation/coercion automatically. The fundamental building blocks are:
Pydantic利用Python类型提示定义数据模式,并自动执行验证与类型转换。其核心组成模块包括:

Models

模型

Primary documentation:
references/concepts/models.md
Define data structures by inheriting from
BaseModel
:
python
from pydantic import BaseModel, Field

class User(BaseModel):
    id: int
    name: str = Field(min_length=1, max_length=100)
    email: str
    age: int | None = None
Key concepts:
  • Basic model usage and instantiation
  • Data conversion and coercion
  • Nested models and relationships
  • Model methods:
    model_validate()
    ,
    model_dump()
    ,
    model_dump_json()
  • Generic models and dynamic creation
  • Immutability with
    frozen=True
API reference:
references/api/base_model/BaseModel.md
- Complete BaseModel class documentation
主文档:
references/concepts/models.md
通过继承
BaseModel
定义数据结构:
python
from pydantic import BaseModel, Field

class User(BaseModel):
    id: int
    name: str = Field(min_length=1, max_length=100)
    email: str
    age: int | None = None
关键概念:
  • 模型基础用法与实例化
  • 数据转换与类型强制转换
  • 嵌套模型与关联关系
  • 模型方法:
    model_validate()
    model_dump()
    model_dump_json()
  • 泛型模型与动态创建
  • 使用
    frozen=True
    实现不可变性
API参考:
references/api/base_model/BaseModel.md
- BaseModel类完整文档

Fields

字段

Primary documentation:
references/concepts/fields.md
Customize field behavior with constraints, defaults, and metadata:
python
from pydantic import BaseModel, Field
from typing import Annotated

class Product(BaseModel):
    name: str = Field(description="Product name")
    price: Annotated[float, Field(gt=0, description="Price in USD")]
    quantity: int = Field(default=0, ge=0)
Key concepts:
  • Field constraints (gt, ge, lt, le, min_length, max_length, pattern)
  • Default values and factories
  • Aliases and validation aliases
  • Required vs optional fields
  • Computed fields with
    @computed_field
API reference:
references/api/fields/
- Field, FieldInfo, and computed field APIs
主文档:
references/concepts/fields.md
通过约束条件、默认值和元数据自定义字段行为:
python
from pydantic import BaseModel, Field
from typing import Annotated

class Product(BaseModel):
    name: str = Field(description="Product name")
    price: Annotated[float, Field(gt=0, description="Price in USD")]
    quantity: int = Field(default=0, ge=0)
关键概念:
  • 字段约束(gt、ge、lt、le、min_length、max_length、pattern)
  • 默认值与工厂函数
  • 别名与验证别名
  • 必填字段与可选字段
  • 使用
    @computed_field
    定义计算字段
API参考:
references/api/fields/
- Field、FieldInfo及计算字段相关API

Validators

验证器

Primary documentation:
references/concepts/validators.md
Implement custom validation logic with field and model validators:
python
from pydantic import BaseModel, field_validator, model_validator

class Account(BaseModel):
    username: str
    password: str
    password_confirm: str

    @field_validator('username')
    @classmethod
    def username_alphanumeric(cls, v):
        assert v.isalnum(), 'must be alphanumeric'
        return v

    @model_validator(mode='after')
    def check_passwords_match(self):
        if self.password != self.password_confirm:
            raise ValueError('passwords do not match')
        return self
Validator types:
  • After validators: Run after Pydantic validation (type-safe, recommended)
  • Before validators: Run before validation (for data preprocessing)
  • Wrap validators: Full control over validation process
  • Plain validators: Replace default validation entirely
API reference:
references/api/functional_validators/
- All validator APIs and decorators
主文档:
references/concepts/validators.md
通过字段验证器和模型验证器实现自定义验证逻辑:
python
from pydantic import BaseModel, field_validator, model_validator

class Account(BaseModel):
    username: str
    password: str
    password_confirm: str

    @field_validator('username')
    @classmethod
    def username_alphanumeric(cls, v):
        assert v.isalnum(), 'must be alphanumeric'
        return v

    @model_validator(mode='after')
    def check_passwords_match(self):
        if self.password != self.password_confirm:
            raise ValueError('passwords do not match')
        return self
验证器类型:
  • 后置验证器: 在Pydantic默认验证后执行(类型安全,推荐使用)
  • 前置验证器: 在默认验证前执行(用于数据预处理)
  • 包装验证器: 完全控制验证流程
  • 纯验证器: 完全替换默认验证逻辑
API参考:
references/api/functional_validators/
- 所有验证器装饰器及类的API

Types

类型

Primary documentation:
references/concepts/types.md
Pydantic supports all Python types plus specialized validation types:
Standard types:
int
,
float
,
str
,
bool
,
list
,
dict
,
set
,
tuple
,
datetime
,
date
,
time
,
UUID
, etc.
Pydantic types: See
references/api/types/
for specialized types:
  • Constrained types:
    conint()
    ,
    constr()
    ,
    confloat()
    , etc.
  • Network types:
    EmailStr
    ,
    AnyUrl
    ,
    IPvAnyAddress
  • Datetime types:
    AwareDatetime
    ,
    NaiveDatetime
    ,
    FutureDate
    ,
    PastDate
  • Special types:
    Json
    ,
    SecretStr
    ,
    PaymentCardNumber
    ,
    FilePath
    ,
    DirectoryPath
Type documentation:
references/concepts/types.md
covers all supported types and patterns
主文档:
references/concepts/types.md
Pydantic支持所有Python原生类型及专用验证类型:
标准类型:
int
float
str
bool
list
dict
set
tuple
datetime
date
time
UUID
Pydantic专用类型: 详见
references/api/types/
获取专用类型文档:
  • 约束类型:
    conint()
    constr()
    confloat()
  • 网络类型:
    EmailStr
    AnyUrl
    IPvAnyAddress
  • 日期时间类型:
    AwareDatetime
    NaiveDatetime
    FutureDate
    PastDate
  • 特殊类型:
    Json
    SecretStr
    PaymentCardNumber
    FilePath
    DirectoryPath
类型文档:
references/concepts/types.md
涵盖所有支持的类型及使用模式

Configuration

配置

Primary documentation:
references/concepts/config.md
Control model behavior with
ConfigDict
:
python
from pydantic import BaseModel, ConfigDict

class User(BaseModel):
    model_config = ConfigDict(
        str_strip_whitespace=True,
        validate_assignment=True,
        frozen=False,
        extra='forbid'
    )
Common settings:
  • extra
    : 'forbid' | 'allow' | 'ignore' - Handle extra fields
  • validate_assignment
    : Validate on attribute assignment
  • frozen
    : Make instances immutable
  • str_strip_whitespace
    : Strip whitespace from strings
  • from_attributes
    : Enable ORM mode for SQLAlchemy, etc.
  • populate_by_name
    : Allow population by field name and alias
API reference:
references/api/config/ConfigDict.md
主文档:
references/concepts/config.md
通过
ConfigDict
控制模型行为:
python
from pydantic import BaseModel, ConfigDict

class User(BaseModel):
    model_config = ConfigDict(
        str_strip_whitespace=True,
        validate_assignment=True,
        frozen=False,
        extra='forbid'
    )
常用配置项:
  • extra
    : 'forbid' | 'allow' | 'ignore' - 处理额外字段的策略
  • validate_assignment
    : 赋值时是否执行验证
  • frozen
    : 是否将实例设为不可变
  • str_strip_whitespace
    : 是否自动去除字符串首尾空格
  • from_attributes
    : 启用ORM模式,支持SQLAlchemy等ORM框架
  • populate_by_name
    : 是否允许通过字段名和别名填充数据
API参考:
references/api/config/ConfigDict.md

Common Workflows

通用工作流

Validation Workflows

验证工作流

Parse untrusted data:
python
user = User.model_validate(data)  # Raises ValidationError if invalid
Parse JSON:
python
user = User.model_validate_json(json_string)
Create without validation:
python
user = User.model_construct(**trusted_data)  # Skip validation for performance
Handle validation errors: See
references/errors/validation_errors.md
解析不可信数据:
python
user = User.model_validate(data)  # 数据无效时抛出ValidationError
解析JSON数据:
python
user = User.model_validate_json(json_string)
跳过验证创建实例:
python
user = User.model_construct(**trusted_data)  # 为优化性能,跳过验证仅用于可信数据
处理验证错误: 详见
references/errors/validation_errors.md

Serialization Workflows

序列化工作流

Primary documentation:
references/concepts/serialization.md
Export to dict:
python
user_dict = user.model_dump()
user_dict = user.model_dump(exclude={'password'})
user_dict = user.model_dump(by_alias=True)
Export to JSON:
python
json_str = user.model_dump_json()
json_str = user.model_dump_json(indent=2, exclude_none=True)
Custom serializers: See
references/api/functional_serializers/
主文档:
references/concepts/serialization.md
导出为字典:
python
user_dict = user.model_dump()
user_dict = user.model_dump(exclude={'password'})
user_dict = user.model_dump(by_alias=True)
导出为JSON:
python
json_str = user.model_dump_json()
json_str = user.model_dump_json(indent=2, exclude_none=True)
自定义序列化器: 详见
references/api/functional_serializers/

JSON Schema Generation

JSON Schema生成

Primary documentation:
references/concepts/json_schema.md
Generate schema:
python
schema = User.model_json_schema()
schema = User.model_json_schema(by_alias=True, mode='serialization')
Customize schema generation: See
references/api/json_schema/GenerateJsonSchema.md
主文档:
references/concepts/json_schema.md
生成Schema:
python
schema = User.model_json_schema()
schema = User.model_json_schema(by_alias=True, mode='serialization')
自定义Schema生成: 详见
references/api/json_schema/GenerateJsonSchema.md

Settings Management

配置管理

Primary documentation:
references/concepts/pydantic_settings.md
For application configuration from environment variables:
python
from pydantic_settings import BaseSettings

class Settings(BaseSettings):
    database_url: str
    api_key: str
    debug: bool = False

    model_config = ConfigDict(env_file='.env')

settings = Settings()
API reference:
references/api/pydantic_settings/
主文档:
references/concepts/pydantic_settings.md
从环境变量加载应用配置:
python
from pydantic_settings import BaseSettings

class Settings(BaseSettings):
    database_url: str
    api_key: str
    debug: bool = False

    model_config = ConfigDict(env_file='.env')

settings = Settings()
API参考:
references/api/pydantic_settings/

Working with ORMs

与ORM框架集成

Primary documentation:
references/examples/orms.md
Pydantic integrates with SQLAlchemy, Django, and other ORMs:
python
from pydantic import BaseModel, ConfigDict

class UserModel(BaseModel):
    model_config = ConfigDict(from_attributes=True)

    id: int
    name: str
主文档:
references/examples/orms.md
Pydantic可与SQLAlchemy、Django等ORM框架集成:
python
from pydantic import BaseModel, ConfigDict

class UserModel(BaseModel):
    model_config = ConfigDict(from_attributes=True)

    id: int
    name: str

Convert ORM instance to Pydantic model

将ORM实例转换为Pydantic模型

user = UserModel.model_validate(sql_user)
undefined
user = UserModel.model_validate(sql_user)
undefined

Advanced Features

高级特性

Dataclasses

数据类

Primary documentation:
references/concepts/dataclasses.md
Use Pydantic with Python dataclasses:
python
from pydantic.dataclasses import dataclass

@dataclass
class User:
    id: int
    name: str
API reference:
references/api/dataclasses/
主文档:
references/concepts/dataclasses.md
在Python数据类中使用Pydantic:
python
from pydantic.dataclasses import dataclass

@dataclass
class User:
    id: int
    name: str
API参考:
references/api/dataclasses/

Type Adapter

类型适配器

Primary documentation:
references/concepts/type_adapter.md
Validate data against any type, not just models:
python
from pydantic import TypeAdapter

ListOfInts = TypeAdapter(list[int])
validated = ListOfInts.validate_python(['1', '2', '3'])
API reference:
references/api/type_adapter/TypeAdapter.md
主文档:
references/concepts/type_adapter.md
针对任意类型(不仅限于模型)验证数据:
python
from pydantic import TypeAdapter

ListOfInts = TypeAdapter(list[int])
validated = ListOfInts.validate_python(['1', '2', '3'])
API参考:
references/api/type_adapter/TypeAdapter.md

Unions and Discriminated Unions

联合类型与区分联合类型

Primary documentation:
references/concepts/unions.md
Handle multiple possible types:
python
from typing import Literal, Union
from pydantic import BaseModel, Field

class Cat(BaseModel):
    pet_type: Literal['cat']
    meows: int

class Dog(BaseModel):
    pet_type: Literal['dog']
    barks: float

class Owner(BaseModel):
    pet: Union[Cat, Dog] = Field(discriminator='pet_type')
主文档:
references/concepts/unions.md
处理多种可能的类型:
python
from typing import Literal, Union
from pydantic import BaseModel, Field

class Cat(BaseModel):
    pet_type: Literal['cat']
    meows: int

class Dog(BaseModel):
    pet_type: Literal['dog']
    barks: float

class Owner(BaseModel):
    pet: Union[Cat, Dog] = Field(discriminator='pet_type')

Aliases

别名

Primary documentation:
references/concepts/alias.md
Map field names for validation and serialization:
python
from pydantic import BaseModel, Field

class User(BaseModel):
    username: str = Field(alias='userName')
API reference:
references/api/aliases/
主文档:
references/concepts/alias.md
为验证和序列化映射字段名:
python
from pydantic import BaseModel, Field

class User(BaseModel):
    username: str = Field(alias='userName')
API参考:
references/api/aliases/

Strict Mode

严格模式

Primary documentation:
references/concepts/strict_mode.md
Enforce strict type validation without coercion:
python
from pydantic import BaseModel, ConfigDict

class StrictModel(BaseModel):
    model_config = ConfigDict(strict=True)

    count: int  # Won't accept '123', only 123
主文档:
references/concepts/strict_mode.md
启用严格类型验证,禁止自动类型转换:
python
from pydantic import BaseModel, ConfigDict

class StrictModel(BaseModel):
    model_config = ConfigDict(strict=True)

    count: int  # 仅接受整数123,不接受字符串'123'

Performance Optimization

性能优化

Primary documentation:
references/concepts/performance.md
Guidelines for optimizing Pydantic performance in production
主文档:
references/concepts/performance.md
生产环境下优化Pydantic性能的指南

Error Handling

错误处理

Validation Errors

验证错误

Complete reference:
references/errors/validation_errors.md
Understand and handle validation errors:
python
from pydantic import ValidationError

try:
    user = User(**data)
except ValidationError as e:
    print(e.errors())  # List of error dictionaries
    print(e.json())    # JSON formatted errors
Error types reference:
references/errors/errors.md
- All validation error codes
完整参考:
references/errors/validation_errors.md
理解并处理验证错误:
python
from pydantic import ValidationError

try:
    user = User(**data)
except ValidationError as e:
    print(e.errors())  # 错误字典列表
    print(e.json())    # JSON格式的错误信息
错误类型参考:
references/errors/errors.md
- 所有验证错误码

Usage Errors

使用错误

Reference:
references/errors/usage_errors.md
Common mistakes and how to fix them
参考:
references/errors/usage_errors.md
常见使用错误及修复方案

API Reference

API参考

Complete API documentation organized by module:
  • references/api/base_model/
    - BaseModel class and create_model()
  • references/api/fields/
    - Field(), FieldInfo, computed fields, private attributes
  • references/api/config/
    - ConfigDict and configuration options
  • references/api/types/
    - All Pydantic types (constrained types, network types, etc.)
  • references/api/functional_validators/
    - Validator decorators and classes
  • references/api/functional_serializers/
    - Serializer decorators and classes
  • references/api/json_schema/
    - JSON schema generation APIs
  • references/api/dataclasses/
    - Pydantic dataclass support
  • references/api/type_adapter/
    - TypeAdapter for validating any type
  • references/api/errors/
    - Error classes
  • references/api/networks/
    - Network validation types (URLs, emails, IPs)
  • references/api/aliases/
    - Alias configuration classes
  • references/api/validate_call/
    - Function validation decorator
  • references/api/version/
    - Version information
按模块组织的完整API文档:
  • references/api/base_model/
    - BaseModel类及create_model()
  • references/api/fields/
    - Field()、FieldInfo、计算字段、私有属性
  • references/api/config/
    - ConfigDict及配置选项
  • references/api/types/
    - 所有Pydantic类型(约束类型、网络类型等)
  • references/api/functional_validators/
    - 验证器装饰器及类
  • references/api/functional_serializers/
    - 序列化器装饰器及类
  • references/api/json_schema/
    - JSON Schema生成相关API
  • references/api/dataclasses/
    - Pydantic数据类支持
  • references/api/type_adapter/
    - 用于验证任意类型的TypeAdapter
  • references/api/errors/
    - 错误类
  • references/api/networks/
    - 网络验证类型(URL、邮箱、IP地址等)
  • references/api/aliases/
    - 别名配置类
  • references/api/validate_call/
    - 函数验证装饰器
  • references/api/version/
    - 版本信息

Examples

示例

Practical examples for common use cases:
  • references/examples/custom_validators.md
    - Building custom validators
  • references/examples/orms.md
    - Integration with SQLAlchemy and Django
  • references/examples/files.md
    - Validating file data (JSON, CSV, etc.)
  • references/examples/requests.md
    - Validating API requests and responses
  • references/examples/queues.md
    - Using Pydantic with message queues
  • references/examples/dynamic_models.md
    - Creating models at runtime
针对常见场景的实用示例:
  • references/examples/custom_validators.md
    - 构建自定义验证器
  • references/examples/orms.md
    - 与SQLAlchemy和Django集成
  • references/examples/files.md
    - 验证文件数据(JSON、CSV等)
  • references/examples/requests.md
    - 验证API请求与响应
  • references/examples/queues.md
    - 在消息队列中使用Pydantic
  • references/examples/dynamic_models.md
    - 运行时创建模型

Development Guidelines

开发指南

Code Quality

代码质量

Linting integration:
references/integrations/linting.md
- Configure ruff, mypy, and other linters
Best practices:
  • Always type annotate fields explicitly
  • Use
    Field()
    for constraints and metadata
  • Prefer after validators over before validators
  • Use discriminated unions for type safety
  • Enable
    validate_assignment
    for mutable models
  • Use
    frozen=True
    for immutable data
  • Configure
    extra='forbid'
    to catch typos
集成代码检查:
references/integrations/linting.md
- 配置ruff、mypy等代码检查工具
最佳实践:
  • 始终显式为字段添加类型注解
  • 使用
    Field()
    定义约束条件和元数据
  • 优先使用后置验证器而非前置验证器
  • 使用区分联合类型确保类型安全
  • 为可变模型启用
    validate_assignment
  • 为不可变数据使用
    frozen=True
  • 配置
    extra='forbid'
    以捕获字段名拼写错误

Production Readiness

生产就绪

Required considerations:
  1. Error handling: Always catch and handle
    ValidationError
  2. Performance: Use
    model_construct()
    for trusted data
  3. Security: Validate all external inputs
  4. Serialization: Test
    model_dump()
    output matches expectations
  5. Schema validation: Generate and validate JSON schemas for APIs
  6. Migration: Follow
    references/migration.md
    when upgrading
必备考虑因素:
  1. 错误处理: 始终捕获并处理
    ValidationError
  2. 性能: 对可信数据使用
    model_construct()
  3. 安全: 验证所有外部输入
  4. 序列化: 测试
    model_dump()
    输出是否符合预期
  5. Schema验证: 为API生成并验证JSON Schema
  6. 迁移: 升级时遵循
    references/migration.md
    的指南

Testing

测试

Validate your models:
python
def test_user_validation():
    # Test valid data
    user = User(id=1, name="Test", email="test@example.com")
    assert user.id == 1

    # Test invalid data
    with pytest.raises(ValidationError):
        User(id="invalid", name="Test")
验证模型:
python
def test_user_validation():
    # 测试有效数据
    user = User(id=1, name="Test", email="test@example.com")
    assert user.id == 1

    # 测试无效数据
    with pytest.raises(ValidationError):
        User(id="invalid", name="Test")

Getting Help

获取帮助

  • Overview:
    references/index.md
    - Introduction to Pydantic
  • Help resources:
    references/help_with_pydantic.md
    - Community support
  • Version policy:
    references/version-policy.md
    - Versioning and deprecation
  • Contributing:
    references/contributing.md
    - How to contribute to Pydantic
  • 概览:
    references/index.md
    - Pydantic介绍
  • 帮助资源:
    references/help_with_pydantic.md
    - 社区支持
  • 版本策略:
    references/version-policy.md
    - 版本管理与废弃策略
  • 贡献指南:
    references/contributing.md
    - 如何为Pydantic做贡献

Version Information

版本信息

This skill covers Pydantic v2.12.5 (December 2025). For migration from v1.x, see
references/migration.md
.
本指南覆盖Pydantic v2.12.5(2025年12月)。从v1.x版本迁移请参考
references/migration.md