python
config_error
ai_generated
true
pydantic.errors.PydanticUserError:如果使用 `@field_validator` 且 `mode='after'`,函数必须为 classmethod。若想使用实例方法,请改用 `@model_validator(mode='after')`。
pydantic.errors.PydanticUserError: If you use `@field_validator` with `mode='after'`, the function must be a classmethod. If you want to use an instance method, use `@model_validator(mode='after')` instead.
ID: python/pydantic-field-validator-info-arg
80%修复率
88%置信度
0证据数
2024-03-05首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 2.x | active | — | — | — |
根因分析
实例方法被 @field_validator 装饰但未加 @classmethod,v2 对 after 模式不允许这样做。
English
An instance method was decorated with @field_validator without @classmethod, which v2 disallows for after-mode.
解决方案
-
95% 成功率
from pydantic import BaseModel, field_validator class M(BaseModel): x: int @field_validator('x', mode='after') @classmethod def check(cls, v): assert v > 0 return v -
90% 成功率
from pydantic import model_validator class M(BaseModel): x: int @model_validator(mode='after') def check(self): assert self.x > 0 return self
无效尝试
常见但无效的做法:
-
45% 失败
Changes validation order; before-mode runs on raw input and may not see coerced types.
-
60% 失败
Pydantic requires classmethod for field validators; staticmethod raises a different error.
-
55% 失败
Bypasses validation pipeline and breaks model_validate paths.