如何更改Pydantic中默认的根验证器响应?

发布于 2025-01-20 23:57:44 字数 888 浏览 2 评论 0原文

假设我有一个简单的 Pydantic 模型,

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

并且我正在尝试验证我的输入,如下所示,

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

这将返回结果为,

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

如何更改 __root__ 的值 在这种情况下还有其他事情吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

摘星┃星的人 2025-01-27 23:57:44

this 讨论和 this 实现,我想说不可能将__根__ root __更改为其他任何东西。

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适合您的用例。

唯一的警告(请参阅验证器 docs ):

验证是在“顺序字段”中进行的。

这意味着,在您的模型定义中,country 必须age age之前进行工作。

但是,当模型实例化时,字段的顺序并不重要。

另请参见 field Ordering

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文