002-第一个Pydantic模型
学习目标
- 掌握BaseModel的基本用法和核心概念
- 学会定义不同类型的字段和约束
- 理解模型的创建、验证和序列化过程
- 掌握模型的基本操作方法
1. BaseModel基础
1.1 什么是BaseModel?
BaseModel是Pydantic的核心类,所有的数据模型都需要继承自这个类。它提供了数据验证、序列化、反序列化等核心功能。
# 文件路径: examples/base_model_intro.py
from pydantic import BaseModel
from typing import Optional
from datetime import datetime
class SimpleModel(BaseModel):
"""最简单的Pydantic模型"""
name: str
age: int
# 创建实例的几种方式
print("=== 创建模型实例 ===")
# 方式1: 关键字参数
user1 = SimpleModel(name="Alice", age=25)
print(f"方式1: {
user1}")
# 方式2: 字典解包
data = {
"name": "Bob", "age": 30}
user2 = SimpleModel(**data)
print(f"方式2: {
user2}")
# 方式3: 使用model_validate(推荐)
user3 = SimpleModel.model_validate({
"name": "Charlie", "age": 35})
print(f"方式3: {
user3}")
1.2 模型的核心方法
# 文件路径: examples/model_methods.py
from pydantic import BaseModel
from typing import Dict, Any
import json
class User(BaseModel):
name: str
age: int
email: Optional[str] = None
user = User(name="张三", age=28, email="zhangsan@example.com")
print("=== 模型核心方法演示 ===")
# 1. 转换为字典
user_dict = user.model_dump()
print(f"转为字典: {
user_dict}")
print(f"类型: {
type(user_dict)}")
# 2. 转换为JSON字符串
user_json = user.model_dump_json()
print(f"转为JSON: {
user_json}")
print(f"类型: {
type(user_json)}")
# 3. 格式化JSON输出
user_json_pretty = user.model_dump_json(indent=2)
print(f"格式化JSON:\n{
user_json_pretty}")
# 4. 获取模型字段信息
print(f"模型字段: {
user.model_fields}")
# 5. 获取模型配置
print(f"模型配置: {
user.model_config}")
# 6. 模型复制
user_copy = user.model_copy()
print(f"复制模型: {
user_copy}")
# 7. 部分更新
user_updated = user.model_copy(update={
"age": 29})
print(f"更新后: {
user_updated}")
2. 字段定义详解
2.1 基础字段类型
# 文件路径: examples/field_types.py
from pydantic import BaseModel
from typing import Optional, List, Dict, Set, Tuple
from datetime import datetime, date, time
from decimal import Decimal
from uuid import UUID
class ComprehensiveModel(BaseModel):
"""展示各种字段类型的模型"""
# 基础类型
string_field: str
integer_field: int
float_field: float
boolean_field: bool
# 可选字段
optional_string: Optional[str] = None
optional_int: Optional[int] = None
# 默认值字段
default_string: str = "默认值"
default_number: int = 42
# 日期时间类型
datetime_field: datetime
date_field: date
time_field: time
# 数值类型
decimal_field: Decimal
# 唯一标识符
uuid_field: UUID
# 集合类型
list_field: List[str]
dict_field: Dict[str, int]
set_field: Set[str]
tuple_field: Tuple[str, int, bool]
# 嵌套列表
nested_list: List[Dict[str, str]]
# 测试数据
test_data = {
"string_field": "Hello World",
"integer_field": 123,
"float_field": 3.14,
"boolean_field": True,
"optional_string": "可选值",
"datetime_field": "2024-12-19T10:30:00",
"date_field": "2024-12-19",
"time_field": "10:30:00",
"decimal_field": "99.99",
"uuid_field": "123e4567-e89b-12d3-a456-426614174000",
"list_field": ["item1", "item2", "item3"],
"dict_field": {
"key1": 1, "key2": 2},
"set_field": ["unique1", "unique2", "unique1"], # 重复项会被去除
"tuple_field": ["string", 42, True],
"nested_list": [
{
"name": "Alice", "role": "admin"},
{
"name": "Bob", "role": "user"}
]
}
try:
model = ComprehensiveModel(**test_data)
print("✅ 模型创建成功:")
print(model.model_dump_json(indent=2))
except Exception as e:
print(f"❌ 创建失败: {
e}")
2.2 Field函数详解
Field函数提供了强大的字段配置功能:
# 文件路径: examples/field_function.py
from pydantic import BaseModel, Field
from typing import Optional
from datetime import datetime
class AdvancedUser(BaseModel):
"""使用Field函数的高级用户模型"""
# 基础约束
id: int = Field(
..., # 必填字段
description="用户唯一标识符",
gt=0, # 大于0
le=999999 # 小于等于999999
)
# 字符串约束
username: str = Field(
...,
description="用户名",
min_length=3,
max_length=20,
pattern=r"^[a-zA-Z0-9_]+$" # 正则表达式
)
# 邮箱字段
email: str = Field(
...,
description="邮箱地址",
examples=["user@example.com"]
)
# 密码字段(不会在序列化时输出)
password: str = Field(
...,
description="用户密码",
min_length=8,
exclude=True # 序列化时排除
)
# 年龄约束
age: Optional[int] = Field(
None,

最低0.47元/天 解锁文章

被折叠的 条评论
为什么被折叠?



