简体   繁体   中英

How to change default root validator response in Pydantic?

Assume that I have a simple Pydantic model as,

from pydantic import BaseModel, root_validator, ValidationError


class Foo(BaseModel):
    age: int
    country: str

    @root_validator()
    @classmethod
    def validate_age_min(cls, values: dict):
        if values["age"] < 18 and values["country"] == "India":
            raise ValueError("Some Error")
        return values

and I'm trying to validate my input as below,

try:
    Foo(age=15, country="India")
except ValidationError as e:
    print(e.errors())

This will return the result as,

[
    {
        "loc": [
            "__root__"
        ],
        "msg": "Some Error",
        "type": "value_error"
    }
]

How can I change the value of __root__ to something else in this case?

Judging by this discussion and this implementation, I would say it's not possible to change __root__ to anything else.

However, in a case like yours, you could work around this limitation with a regular validator() , for example, like this:

from pydantic import BaseModel, validator

class Foo(BaseModel):
    country: str
    age: int

    @validator("age")
    def validate_age_min(cls, v: int, values: dict):
        if values["country"] == "India" and v < 18:
            raise ValueError("Some Error")
        return v

Now, the validation:

try:
    Foo(age=15, country="India")
except ValidationError as e:
    print(e.errors())

will show an error like this:

[
  {
    "loc": [
      "age"
    ],
    "msg": "Some Error",
    "type": "value_error"
  }
]

which might be better suited for your use case.

The only caveat (see end of first section in the Validator docs ):

Validation is done in the order fields are defined.

Which means, in your model definition , country must go before age for this to work.

However, the order of fields doesn't matter when the model gets instantiated .

See also Field Ordering .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM