解决 Pydantic v2 ORM mode 报错 model_config 被覆盖
· 阅读需 2 分钟
TL;DR
Pydantic v2 不再支持 class Config,需要用 model_config = ConfigDict(from_attributes=True)。如果你的模型有 model_config 字段,必须重命名避免与保留字冲突。
问题现象
报错 1:class Config 不生效
from pydantic import BaseModel
class AgentResponse(BaseModel):
id: str
name: str
class Config:
orm_mode = True # v1 写法
PydanticUserError: `orm_mode` is not a valid config option. Did you mean `from_attributes`?
报错 2:model_config 字段冲突
class Agent(BaseModel):
id: str
model_config: dict # 业务字段,存储 LLM 配置
model_config = ConfigDict(from_attributes=True)
# TypeError: 'dict' object is not callable
模型中有个业务字段叫 model_config(存储 LLM 配置),与 Pydantic v2 保留字冲突。