pydantic-dev
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChinesePydantic 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 for setup instructions and optional dependencies
references/install.mdCore Philosophy: See for Pydantic's design principles and when to use it
references/why.mdMigration from v1: See for upgrading from Pydantic v1.x
references/migration.md安装说明: 详见 获取安装步骤及可选依赖配置
references/install.md核心设计理念: 详见 了解Pydantic的设计原则及适用场景
references/why.md从v1版本迁移: 详见 获取从Pydantic v1.x升级的指南
references/migration.mdCore 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.mdDefine data structures by inheriting from :
BaseModelpython
from pydantic import BaseModel, Field
class User(BaseModel):
id: int
name: str = Field(min_length=1, max_length=100)
email: str
age: int | None = NoneKey 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: - Complete BaseModel class documentation
references/api/base_model/BaseModel.md主文档:
references/concepts/models.md通过继承定义数据结构:
BaseModelpython
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参考: - BaseModel类完整文档
references/api/base_model/BaseModel.mdFields
字段
Primary documentation:
references/concepts/fields.mdCustomize 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: - Field, FieldInfo, and computed field APIs
references/api/fields/主文档:
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参考: - Field、FieldInfo及计算字段相关API
references/api/fields/Validators
验证器
Primary documentation:
references/concepts/validators.mdImplement 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 selfValidator 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: - All validator APIs and decorators
references/api/functional_validators/主文档:
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参考: - 所有验证器装饰器及类的API
references/api/functional_validators/Types
类型
Primary documentation:
references/concepts/types.mdPydantic supports all Python types plus specialized validation types:
Standard types: , , , , , , , , , , , , etc.
intfloatstrboollistdictsettupledatetimedatetimeUUIDPydantic types: See for specialized types:
references/api/types/- Constrained types: ,
conint(),constr(), etc.confloat() - Network types: ,
EmailStr,AnyUrlIPvAnyAddress - Datetime types: ,
AwareDatetime,NaiveDatetime,FutureDatePastDate - Special types: ,
Json,SecretStr,PaymentCardNumber,FilePathDirectoryPath
Type documentation: covers all supported types and patterns
references/concepts/types.md主文档:
references/concepts/types.mdPydantic支持所有Python原生类型及专用验证类型:
标准类型: 、、、、、、、、、、、等
intfloatstrboollistdictsettupledatetimedatetimeUUIDPydantic专用类型: 详见获取专用类型文档:
references/api/types/- 约束类型:、
conint()、constr()等confloat() - 网络类型:、
EmailStr、AnyUrlIPvAnyAddress - 日期时间类型:、
AwareDatetime、NaiveDatetime、FutureDatePastDate - 特殊类型:、
Json、SecretStr、PaymentCardNumber、FilePathDirectoryPath
类型文档: 涵盖所有支持的类型及使用模式
references/concepts/types.mdConfiguration
配置
Primary documentation:
references/concepts/config.mdControl model behavior with :
ConfigDictpython
from pydantic import BaseModel, ConfigDict
class User(BaseModel):
model_config = ConfigDict(
str_strip_whitespace=True,
validate_assignment=True,
frozen=False,
extra='forbid'
)Common settings:
- : 'forbid' | 'allow' | 'ignore' - Handle extra fields
extra - : Validate on attribute assignment
validate_assignment - : Make instances immutable
frozen - : Strip whitespace from strings
str_strip_whitespace - : Enable ORM mode for SQLAlchemy, etc.
from_attributes - : Allow population by field name and alias
populate_by_name
API reference:
references/api/config/ConfigDict.md主文档:
references/concepts/config.md通过控制模型行为:
ConfigDictpython
from pydantic import BaseModel, ConfigDict
class User(BaseModel):
model_config = ConfigDict(
str_strip_whitespace=True,
validate_assignment=True,
frozen=False,
extra='forbid'
)常用配置项:
- : 'forbid' | 'allow' | 'ignore' - 处理额外字段的策略
extra - : 赋值时是否执行验证
validate_assignment - : 是否将实例设为不可变
frozen - : 是否自动去除字符串首尾空格
str_strip_whitespace - : 启用ORM模式,支持SQLAlchemy等ORM框架
from_attributes - : 是否允许通过字段名和别名填充数据
populate_by_name
API参考:
references/api/config/ConfigDict.mdCommon Workflows
通用工作流
Validation Workflows
验证工作流
Parse untrusted data:
python
user = User.model_validate(data) # Raises ValidationError if invalidParse JSON:
python
user = User.model_validate_json(json_string)Create without validation:
python
user = User.model_construct(**trusted_data) # Skip validation for performanceHandle 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.mdSerialization Workflows
序列化工作流
Primary documentation:
references/concepts/serialization.mdExport 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.mdGenerate 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.mdSettings Management
配置管理
Primary documentation:
references/concepts/pydantic_settings.mdFor 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.mdPydantic 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.mdPydantic可与SQLAlchemy、Django等ORM框架集成:
python
from pydantic import BaseModel, ConfigDict
class UserModel(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: int
name: strConvert ORM instance to Pydantic model
将ORM实例转换为Pydantic模型
user = UserModel.model_validate(sql_user)
undefineduser = UserModel.model_validate(sql_user)
undefinedAdvanced Features
高级特性
Dataclasses
数据类
Primary documentation:
references/concepts/dataclasses.mdUse Pydantic with Python dataclasses:
python
from pydantic.dataclasses import dataclass
@dataclass
class User:
id: int
name: strAPI reference:
references/api/dataclasses/主文档:
references/concepts/dataclasses.md在Python数据类中使用Pydantic:
python
from pydantic.dataclasses import dataclass
@dataclass
class User:
id: int
name: strAPI参考:
references/api/dataclasses/Type Adapter
类型适配器
Primary documentation:
references/concepts/type_adapter.mdValidate 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.mdUnions and Discriminated Unions
联合类型与区分联合类型
Primary documentation:
references/concepts/unions.mdHandle 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.mdMap 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.mdEnforce 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.mdGuidelines for optimizing Pydantic performance in production
主文档:
references/concepts/performance.md生产环境下优化Pydantic性能的指南
Error Handling
错误处理
Validation Errors
验证错误
Complete reference:
references/errors/validation_errors.mdUnderstand 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 errorsError types reference: - All validation error codes
references/errors/errors.md完整参考:
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.mdUsage Errors
使用错误
Reference:
references/errors/usage_errors.mdCommon mistakes and how to fix them
参考:
references/errors/usage_errors.md常见使用错误及修复方案
API Reference
API参考
Complete API documentation organized by module:
- - BaseModel class and create_model()
references/api/base_model/ - - Field(), FieldInfo, computed fields, private attributes
references/api/fields/ - - ConfigDict and configuration options
references/api/config/ - - All Pydantic types (constrained types, network types, etc.)
references/api/types/ - - Validator decorators and classes
references/api/functional_validators/ - - Serializer decorators and classes
references/api/functional_serializers/ - - JSON schema generation APIs
references/api/json_schema/ - - Pydantic dataclass support
references/api/dataclasses/ - - TypeAdapter for validating any type
references/api/type_adapter/ - - Error classes
references/api/errors/ - - Network validation types (URLs, emails, IPs)
references/api/networks/ - - Alias configuration classes
references/api/aliases/ - - Function validation decorator
references/api/validate_call/ - - Version information
references/api/version/
按模块组织的完整API文档:
- - BaseModel类及create_model()
references/api/base_model/ - - Field()、FieldInfo、计算字段、私有属性
references/api/fields/ - - ConfigDict及配置选项
references/api/config/ - - 所有Pydantic类型(约束类型、网络类型等)
references/api/types/ - - 验证器装饰器及类
references/api/functional_validators/ - - 序列化器装饰器及类
references/api/functional_serializers/ - - JSON Schema生成相关API
references/api/json_schema/ - - Pydantic数据类支持
references/api/dataclasses/ - - 用于验证任意类型的TypeAdapter
references/api/type_adapter/ - - 错误类
references/api/errors/ - - 网络验证类型(URL、邮箱、IP地址等)
references/api/networks/ - - 别名配置类
references/api/aliases/ - - 函数验证装饰器
references/api/validate_call/ - - 版本信息
references/api/version/
Examples
示例
Practical examples for common use cases:
- - Building custom validators
references/examples/custom_validators.md - - Integration with SQLAlchemy and Django
references/examples/orms.md - - Validating file data (JSON, CSV, etc.)
references/examples/files.md - - Validating API requests and responses
references/examples/requests.md - - Using Pydantic with message queues
references/examples/queues.md - - Creating models at runtime
references/examples/dynamic_models.md
针对常见场景的实用示例:
- - 构建自定义验证器
references/examples/custom_validators.md - - 与SQLAlchemy和Django集成
references/examples/orms.md - - 验证文件数据(JSON、CSV等)
references/examples/files.md - - 验证API请求与响应
references/examples/requests.md - - 在消息队列中使用Pydantic
references/examples/queues.md - - 运行时创建模型
references/examples/dynamic_models.md
Development Guidelines
开发指南
Code Quality
代码质量
Linting integration: - Configure ruff, mypy, and other linters
references/integrations/linting.mdBest practices:
- Always type annotate fields explicitly
- Use for constraints and metadata
Field() - Prefer after validators over before validators
- Use discriminated unions for type safety
- Enable for mutable models
validate_assignment - Use for immutable data
frozen=True - Configure to catch typos
extra='forbid'
集成代码检查: - 配置ruff、mypy等代码检查工具
references/integrations/linting.md最佳实践:
- 始终显式为字段添加类型注解
- 使用定义约束条件和元数据
Field() - 优先使用后置验证器而非前置验证器
- 使用区分联合类型确保类型安全
- 为可变模型启用
validate_assignment - 为不可变数据使用
frozen=True - 配置以捕获字段名拼写错误
extra='forbid'
Production Readiness
生产就绪
Required considerations:
- Error handling: Always catch and handle
ValidationError - Performance: Use for trusted data
model_construct() - Security: Validate all external inputs
- Serialization: Test output matches expectations
model_dump() - Schema validation: Generate and validate JSON schemas for APIs
- Migration: Follow when upgrading
references/migration.md
必备考虑因素:
- 错误处理: 始终捕获并处理
ValidationError - 性能: 对可信数据使用
model_construct() - 安全: 验证所有外部输入
- 序列化: 测试输出是否符合预期
model_dump() - Schema验证: 为API生成并验证JSON Schema
- 迁移: 升级时遵循的指南
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: - Introduction to Pydantic
references/index.md - Help resources: - Community support
references/help_with_pydantic.md - Version policy: - Versioning and deprecation
references/version-policy.md - Contributing: - How to contribute to Pydantic
references/contributing.md
- 概览: - Pydantic介绍
references/index.md - 帮助资源: - 社区支持
references/help_with_pydantic.md - 版本策略: - 版本管理与废弃策略
references/version-policy.md - 贡献指南: - 如何为Pydantic做贡献
references/contributing.md
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