python
type_error
ai_generated
true
pydantic.errors.PydanticUserError: @field_validator 'check_email' 应为 classmethod 或 staticmethod。请用 @classmethod 或 @staticmethod 包装。
pydantic.errors.PydanticUserError: @field_validator 'check_email' should be a classmethod or a staticmethod. Wrap the function with @classmethod or @staticmethod.
ID: python/pydantic-field-validator-signature-error
80%修复率
90%置信度
0证据数
2024-03-15首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 2.x | active | — | — | — |
根因分析
在 Pydantic v2 中,@field_validator 必须装饰 classmethod(或 staticmethod)。缺少 @classmethod 装饰器会在类定义时引发 PydanticUserError。
English
In Pydantic v2, @field_validator must decorate a classmethod (or staticmethod). Missing the @classmethod decorator causes a PydanticUserError at class definition time.
解决方案
-
98% 成功率
from pydantic import BaseModel, field_validator class User(BaseModel): email: str @field_validator('email') @classmethod def check_email(cls, v): assert '@' in v return v -
95% 成功率
from pydantic import BaseModel, field_validator class User(BaseModel): email: str @field_validator('email') @staticmethod def check_email(v): return v.lower()
无效尝试
常见但无效的做法:
-
80% 失败
Decorator order matters: @field_validator must be the outermost decorator, i.e., listed first.
-
60% 失败
@validator is deprecated in v2 and raises PydanticDeprecatedSince20 warnings; it also still requires classmethod semantics.