Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Subclass validator each item docs #1592

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions changes/1566-samueldeklund.md
@@ -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.
36 changes: 36 additions & 0 deletions docs/examples/validators_subclass_each_item.py
@@ -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)
10 changes: 10 additions & 0 deletions docs/usage/validators.md
Expand Up @@ -50,6 +50,16 @@ A few more things to note:
* passing `each_item=True` will result in the validator being applied to individual values
(e.g. of `List`, `Dict`, `Set`, etc.), rather than the whole object

## Subclass Validators and `each_item`

If using a validator with a subclass that references a `List` type field on a parent class, using `each_item=True` will
cause the validator not to run; instead, the list must be iterated over programatically.

```py
{!.tmp_examples/validators_subclass_each_item.py!}
```
_(This script is complete, it should run "as is")_

## Validate Always

For performance reasons, by default validators are not called for fields when a value is not supplied.
Expand Down