第七章:模型配置 ConfigDict
每个模型都可以通过 model_config 调整整体行为:
python
from pydantic import BaseModel, ConfigDict
class User(BaseModel):
model_config = ConfigDict(
strict=True, # 严格模式:"18" 不再自动转成 18
extra="forbid", # 禁止传入未声明的字段
validate_assignment=True, # 赋值时也校验
frozen=False, # True 则实例不可变
str_strip_whitespace=True,# 字符串自动去首尾空格
populate_by_name=True, # 允许用字段名(而非别名)传参
)
name: str
age: int7.1 重点配置详解
extra:多出来的字段怎么办?
python
class A(BaseModel):
model_config = ConfigDict(extra="forbid") # ignore(默认,静默丢弃) / allow(保留) / forbid(报错)API 开发中推荐 forbid:调用方多传了字段通常是 bug,静默吞掉会掩盖问题。
strict:严格模式
默认是"lax"(宽松)模式,"18" → 18、"true" → True 都自动转。开启 strict 后类型必须完全匹配。也可以只对单个字段严格:age: int = Field(strict=True)。
validate_assignment:创建之后也不放松
python
class User(BaseModel):
model_config = ConfigDict(validate_assignment=True)
age: int
user = User(age=18)
user.age = "abc" # 没有这个配置就不会报错;有了它,赋值同样触发校验7.2 从属性创建(ORM 模式)
从 SQLAlchemy 等 ORM 对象直接构建模型:
python
class UserOut(BaseModel):
model_config = ConfigDict(from_attributes=True) # v1 叫 orm_mode
id: int
name: str
# db_user 是个 ORM 对象,有 .id 和 .name 属性
user_out = UserOut.model_validate(db_user)FastAPI 项目里这个配置几乎必开。