Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ImportError: cannot import name 'field_validator' from 'pydantic'

I am getting error: ImportError: cannot import name 'field_validator' from 'pydantic' while writing a custom validator on fields of my model class generated from a schema. Here is how I am importing:

from pydantic import field_validator

Versions being used: pydantic version: pypi:pydantic:1.10.7 datamodel-code-generator: pypi:datamodel-code-generator:0.17.1

Please help me in identifying the issue.

like image 747
shane Avatar asked Oct 27 '25 06:10

shane


1 Answers

field_validator() is a pydantic v2 function, so if you want to use it, upgrade your pydantic version to a more recent version: pip install pydantic -U.

However, if you're stuck on v1 (perhaps restricted to v1 due to conflict with another library such as langchain), then consider using validator() instead.

There are some differences in the function calls especially if you want a more complex validator but at their most basic level, they are very similar. The following example shows a way to validate a user model in both in v1 and v2. You can verify that they are slightly different, especially their error signatures.

Pydantic v1:

from pydantic.v1 import BaseModel, Field, validator, ValidationError

class UserModel(BaseModel):
    name: str
    password1: str = Field("abc")
    password2: str

    @validator("name")
    def name_must_contain_space(cls, v: str) -> str:
        if " " not in v:
            raise ValueError("must contain a space")
        return v.title()

    @validator("password2")
    def passwords_match(cls, v: str, values: dict[str, str]) -> str:
        if v != values.get("password1"):
            raise ValueError("passwords do not match")
        return v


try:
    UserModel(name="John Doe", password2="xyz")
except ValidationError as err:
    print(err)

Pydantic v2:

from pydantic import BaseModel, Field, field_validator, ValidationInfo, ValidationError

class UserModel(BaseModel):
    name: str
    password1: str = Field("abc")
    password2: str

    @field_validator("name")
    def name_must_contain_space(cls, v: str) -> str:
        if " " not in v:
            raise ValueError("must contain a space")
        return v.title()

    @field_validator("password2")
    def passwords_match(cls, v: str, values: ValidationInfo) -> str:
        if v != values.data.get("password1"):
            raise ValueError("passwords do not match")
        return v


try:
    UserModel(name="John Doe", password2="xyz")
except ValidationError as err:
    print(err)
like image 60
cottontail Avatar answered Oct 28 '25 21:10

cottontail



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!