第三章:字段类型:一切的基础
Pydantic 支持的类型远比你想象的多。掌握它们,建模就成功了一半。
3.1 基本类型
python
class Demo(BaseModel):
s: str # 字符串
i: int # 整数
f: float # 浮点数
b: bool # 布尔值
b2: bytes # 字节
n: None # 只能是 None注意 bool 的解析规则:"true"、"yes"、"1"、1 都会被转成 True,做接口开发时很方便。
3.2 容器类型
python
class Inventory(BaseModel):
tags: list[str] # 字符串列表
scores: dict[str, float] # 键是 str、值是 float 的字典
point: tuple[int, int] # 固定结构的元组
unique_ids: set[int] # 集合(自动去重)
matrix: list[list[int]] # 嵌套列表,随便套容器会 递归校验:list[int] 里混进一个 "abc",照样报错,并且错误信息能定位到具体是第几个元素。
3.3 可选与默认
python
class Profile(BaseModel):
nickname: str | None = None # 可以为 None,且可以不传
bio: str | None # 可以为 None,但必须显式传!
level: int = 1 # 有默认值,可以不传⚠️ 初学者最常踩的坑:str | None 只表示"值可以是 None",不代表这个字段可以不传。想让它可省略,必须给默认值 = None。
3.4 常用标准库类型
python
from datetime import datetime, date
from decimal import Decimal
from pathlib import Path
from uuid import UUID
class Order(BaseModel):
order_id: UUID # 自动解析 "123e4567-..." 这样的字符串
created_at: datetime # 自动解析 "2026-10-10T19:54:00"
pay_date: date
amount: Decimal # 金额请用 Decimal,别用 float!
receipt_path: Path💡 经验法则:涉及钱,永远用 Decimal,避免浮点精度问题(0.1 + 0.2 != 0.3)。
3.5 Pydantic 自带的增强类型
python
from pydantic import BaseModel, EmailStr, HttpUrl, SecretStr, PositiveInt
class Account(BaseModel):
email: EmailStr # 校验邮箱格式(需 pip install "pydantic[email]")
website: HttpUrl # 校验 URL 格式
password: SecretStr # 打印时显示 **********,防止日志泄密
age: PositiveInt # 必须是正整数
ratio: confloat = None # 见下常用的数值约束类型:PositiveInt、NegativeInt、NonNegativeInt、PositiveFloat 等,一行顶一个 if 判断。