How To Validate Complex List Types In Pydantic?
Why does pydantic not validate an argument that is the list of Foo objects but throws ValidationError when the argument is a list of primitive types? Can I enforce the validation o
Solution 1:
When working with pydantic
, it should be remembered that:
pydantic is primarily a parsing library, not a validation library. Validation is a means to an end: building a model which conforms to the types and constraints provided.
In other words, pydantic guarantees the types and constraints of the output model, not the input data.
For additional validation of incoming data, a tool is provided - validators. For example:
classSpam(BaseModel):
foos: List[Foo]
@validator('foos', pre=True, each_item=True)defcheck_squares(cls, v):
assertisinstance(v, Foo), "Foo is only allowed"return v
Solution 2:
You can't validate the value like kind: str = "foo"
. You have to use Field in order to validate values of a variable.
Try:
from typing importListimport pydantic
from pydantic import BaseModel, Field
classFoo(BaseModel):
kind: str = Field(const="foo", default="foo")
classBar(BaseModel):
kind: str = Field(const="bar", default="bar")
classSpam(BaseModel):
foos: List[Foo]
try:
Spam.parse_obj({'foos': [{'kind': 'bar'}]})
except pydantic.ValidationError as e:
print(e)
Post a Comment for "How To Validate Complex List Types In Pydantic?"