To extend on the answer of Rahul R
, this example shows in more detail how to use the pydantic
validators.
This example contains all the necessary information to answer your question.
import pydantic
class Parent(pydantic.BaseModel):
name: str
comments: str
class Customer(Parent):
address: str
phone: str
@pydantic.validator("name", "comments", "address", "phone")
@classmethod
def validate_all_fields_one_by_one(cls, field_value):
print(f"{cls}: Field value {field_value}")
return field_value
@pydantic.validator("phone")
@classmethod
def validate_one_field_using_the_others(cls, field_value, values, field, config):
parent_class_name = values["name"]
parent_class_address = values["address"]
print(f"{field_value} is the {field.name} of {parent_class_name}")
return field_value
Customer(name="Peter", comments="Pydantic User", address="Home", phone="117")
Output
<class '__main__.Customer'>: Field value Peter
<class '__main__.Customer'>: Field value Pydantic User
<class '__main__.Customer'>: Field value Home
<class '__main__.Customer'>: Field value 117
117 is the phone number of Peter
Customer(name='Peter', comments='Pydantic User', address='Home', phone='117')
To answer your question in more detail:
Add the fields to validate to the @validator
decorator directly above the validation function.
@validator("name")
uses the field value of "name"
(e.g. "Peter"
) as input to the validation function. All fields of the class and its parent classes can be added to the @validator
decorator.
- the validation function (
validate_all_fields_one_by_one
) then uses the field value as the second argument (field_value
) for which to validate the input. The return value of the validation function is written to the class field. The signature of the validation function is def validate_something(cls, field_value)
where the function and variable names can be chosen arbitrarily (but the first argument should be cls
). According to Arjan (https://youtu.be/Vj-iU-8_xLs?t=329), also the @classmethod
decorator should be added.
If the goal is to validate one field by using other (already validated) fields of the parent and child class, the full signature of the validation function is def validate_something(cls, field_value, values, field, config)
(the argument names values
,field
and config
must match) where the value of the fields can be accessed with the field name as key (e.g. values["comments"]
).
from pydantic import root_validator
raises anImportError
, this is most probably because you do not have the right version ofpydantic
... Which version do you use ? – smarie