'Multiple checks for custom type in Pydantic
Is there any way to achieve a multiple Exception raise call for a custom type?
from pydantic import BaseModel
class CustomType(object):
@classmethod
def validate_first(cls, *args, **kwargs):
raise ValueError("first")
return cls(*args, **kwargs)
@classmethod
def validate_second(cls, *args, **kwargs):
raise ValueError("second")
return cls(*args, **kwargs)
@classmethod
def __get_validators__(cls):
yield cls.validate_first
yield cls.validate_second
class MyModel(BaseModel):
model_field: CustomType
data = {
"model_field": 1,
}
MyModel(**data)
I see only the first ValidationError being raised
ValidationError: 1 validation error for MyModel
model_field
first (type=value_error)
But I would like to get this result
ValidationError: 1 validation error for MyModel
model_field
first (type=value_error)
model_field
second (type=value_error)
As you know, if an exception is raised in the generator, it terminates (raises StopIteration)
Is there a way around this?
Solution 1:[1]
I believe there is no way around that and you have to raise a single ValueError for all the validations of a field, but you can pass a list or a dict to a ValueError if that helps:
import pydantic
class Foo(pydantic.BaseModel):
bar: str
baz: str
@pydantic.validator("bar")
def _validate_bar(cls, bar: str) -> str:
raise ValueError(["first", "second"])
@pydantic.validator("baz")
def _validate_baz(cls, bar: str) -> str:
raise ValueError({"first": "blah blah", "second": "blah blah"})
Foo(bar="a", baz="b")
# Output:
# pydantic.error_wrappers.ValidationError: 2 validation errors for Foo
# bar
# ['first', 'second'] (type=value_error)
# baz
# {'first': 'blah blah', 'second': 'blah blah'} (type=value_error)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Hernán Alarcón |
