python runtime_error ai_generated true

PydanticUserError: 'email' 上的 @field_validator 需要 classmethod,但装饰器被应用于普通方法。请在 @field_validator 下方添加 @classmethod。

PydanticUserError: @field_validator on 'email' requires a classmethod, but the decorator was applied to a regular method. Add @classmethod below @field_validator.

ID: python/pydantic-validator-not-classmethod

其他格式: JSON · Markdown 中文 · English
80%修复率
90%置信度
0证据数
2024-01-22首次发现

版本兼容性

版本状态引入弃用备注
2.x active — — —

根因分析

在 Pydantic v2 中,field_validator 必须装饰 classmethod;省略 @classmethod 会在类定义时引发 PydanticUserError。

English

In Pydantic v2, field_validator must decorate a classmethod; omitting @classmethod causes a PydanticUserError at class definition time.

generic

解决方案

  1. 99% 成功率
    from pydantic import field_validator
    class User(BaseModel):
        email: str
        @field_validator('email')
        @classmethod
        def check_email(cls, v):
            return v.lower()
  2. 94% 成功率
    from typing import Annotated
    from pydantic import AfterValidator
    Email = Annotated[str, AfterValidator(lambda v: v.lower())]

无效尝试

常见但无效的做法:

  1. 95% 失败

    field_validator explicitly checks for classmethod; staticmethod is rejected.

  2. 90% 失败

    Validators must be defined inside the model class to be registered.