* moving docs to mkdocs * transfering readme to md and more * fixing build * splitting usage.md * improving schema.md and index.md * fix make_history.rst * models intro * working on data conversation and required fields * more fixes to models.md * list all standard types supported * list of pydantic types * tweaks * update links in code * Apply suggestions from code review incorporate @dmontagu's suggestions. Co-Authored-By: dmontagu <35119617+dmontagu@users.noreply.github.com> * Apply suggestions from code review more missed suggestions. Co-Authored-By: dmontagu <35119617+dmontagu@users.noreply.github.com> * Apply suggestions from code review more corrects. * cleanup * Field order warning * fix and regenerate benchmarks * format examples better, cleanup * improve schema mapping table * correct highlighting file types in schema.md * add redirects in javascript * add logo
3.8 KiB
Custom validation and complex relationships between objects can be achieved using the validator decorator.
{!./examples/validators_simple.py!}
(This script is complete, it should run "as is")
A few things to note on validators:
- validators are "class methods", the first value they receive here will be the
UserModelnot an instance ofUserModel - their signature can be
(cls, value)or(cls, value, values, config, field). Any subset ofvalues,configandfieldis also permitted, eg.(cls, value, field), however due to the way validators are inspected, the variadic key word argument ("**kwargs") must be calledkwargs. - validators should either return the new value or raise a
ValueError,TypeError, orAssertionError(assertstatements may be used).
!!! warning
If you make use of assert statements, keep in mind that running
Python with the -O optimization flag
disables assert statements, and validators will stop working.
-
where validators rely on other values, you should be aware that:
-
Validation is done in the order fields are defined, eg. here
password2has access topassword1(andname), butpassword1does not have access topassword2. See Field Ordering for more information on how fields are ordered -
If validation fails on another field (or that field is missing) it will not be included in
values, henceif 'password1' in values and ...in this example.
-
Pre and per-item validators
Validators can do a few more complex things:
{!./examples/validators_pre_item.py!}
(This script is complete, it should run "as is")
A few more things to note:
- a single validator can apply to multiple fields, either by defining multiple fields or by the special value
'*'which means that validator will be called for all fields. - the keyword argument
prewill cause validators to be called prior to other validation - the
each_itemkeyword argument will mean validators are applied to individual values (eg. ofList,Dict,Setetc.) not the whole object
Validate Always
For performance reasons by default validators are not called for fields where the value is not supplied. However there are situations where it's useful or required to always call the validator, e.g. to set a dynamic default value.
{!./examples/validators_always.py!}
(This script is complete, it should run "as is")
You'll often want to use this together with pre since otherwise with always=True
pydantic would try to validate the default None which would cause an error.
Root Validators
Validation can also be performed on the entire model's data.
{!./examples/validators_root.py!}
(This script is complete, it should run "as is")
As with field validators, root validators can be pre=True in which case they're called before field
validation occurs with the raw input data, or pre=False (the default) in which case
they're called after field validation.
Field validation will not occur if "pre" root validators raise an error. As with field validators,
"post" (e.g. non pre) root validators will be called even if field validation fails; the values argument will
be a dict containing the values which passed field validation and field defaults where applicable.
Field Checks
On class creation validators are checked to confirm that the fields they specify actually exist on the model.
Occasionally however this is not wanted: when you define a validator to validate fields on inheriting models.
In this case you should set check_fields=False on the validator.
Dataclass Validators
Validators also work in Dataclasses.
{!./examples/validators_dataclass.py!}
(This script is complete, it should run "as is")