python config_error ai_generated true

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

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2024-03-05First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
2.x active

Root Cause

An instance method was decorated with @field_validator without @classmethod, which v2 disallows for after-mode.

generic

中文

实例方法被 @field_validator 装饰但未加 @classmethod,v2 对 after 模式不允许这样做。

Workarounds

  1. 95% success
    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
  2. 90% success
    from pydantic import model_validator
    class M(BaseModel):
        x: int
        @model_validator(mode='after')
        def check(self):
            assert self.x > 0
            return self

Dead Ends

Common approaches that don't work:

  1. 45% fail

    Changes validation order; before-mode runs on raw input and may not see coerced types.

  2. 60% fail

    Pydantic requires classmethod for field validators; staticmethod raises a different error.

  3. 55% fail

    Bypasses validation pipeline and breaks model_validate paths.