Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
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
- Loading branch information
1 parent
7ac9faf
commit 7bd635c
Showing
3 changed files
with
47 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
Subclass validators do not run when referencing a `List` field defined in a parent class when `each_item=True`. Added an example to the docs illustrating this. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters