先搞清楚 Pydantic 到底在帮你做什么
很多人把 Pydantic 理解成"字段校验工具",但它实际做的事比这多得多:
运行时类型校验:Python 的 type hints 只是标注,运行时不会真的检查。Pydantic 会在数据进来的那一刻做真正的校验。
from pydantic import BaseModel
class OrderItem(BaseModel):
product_id: int
quantity: int
price: float
# type hints 不会拦住这个,但 Pydantic 会
OrderItem(product_id="abc", quantity=2, price=10.0)
# ValidationError: Input should be a valid integer
自动类型转换:合理的类型会被自动转换,而不是直接拒绝。
# 字符串 "3" 会被自动转换成 int 3
item = OrderItem(product_id="123", quantity="3", price="10.5")
print(item.quantity) # 3 (int, 不是 str)
序列化控制:你可以精确控制哪些字段对外暴露、怎么命名、怎么转换。
class UserResponse(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: int
username: str
email: str
# password 不在这里 → 不会被序列化到响应里
这三件事加在一起,Pydantic 在 FastAPI 里的真正角色是:请求进来时守门,响应出去时过滤,中间还帮你把类型理顺。
理解了这一点,再来看为什么模型要拆分就会清楚很多。