Files
pydantic/docs/examples/validators_subclass_each_item.py
Samuel Eklund 7bd635c21c Subclass validator each item docs (#1592)
* add description of subclass each_item scenario

* add example of subclass validator with each_item

* each_item causes validator to not run when parent class has List field #1566
2020-06-27 14:51:18 +01:00

37 lines
861 B
Python

from typing import List
from pydantic import BaseModel, ValidationError, validator
class ParentModel(BaseModel):
names: List[str]
class ChildModel(ParentModel):
@validator('names', each_item=True)
def check_names_not_empty(cls, v):
assert v != '', 'Empty strings are not allowed.'
return v
# This will NOT raise a ValidationError because the validator was not called
try:
child = ChildModel(names=['Alice', 'Bob', 'Eve', ''])
except ValidationError as e:
print(e)
else:
print('No ValidationError caught.')
class ChildModel2(ParentModel):
@validator('names')
def check_names_not_empty(cls, v):
for name in v:
assert name != '', 'Empty strings are not allowed.'
return v
try:
child = ChildModel2(names=['Alice', 'Bob', 'Eve', ''])
except ValidationError as e:
print(e)