如何更改Pydantic中默认的根验证器响应?
假设我有一个简单的 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
以 this 讨论和 this 实现,我想说不可能将
__根__ root __
更改为其他任何东西。However, in a case like yours, you could work around this limitation with a regular
validator()
, for example, like this:Now, the validation:
will show an error like this:
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:Now, the validation:
will show an error like this:
which might be better suited for your use case.
The only caveat (see end of first section in the Validator docs):
Which means, in your model definition,
country
must go beforeage
for this to work.However, the order of fields doesn't matter when the model gets instantiated.
See also Field Ordering.