5
votes

I want to validate three model Fields of pydantic model. To Do this i am importing root_validator from pydantic. Getting below error. I found this in the https://pydantic-docs.helpmanual.io/usage/validators/#root-validators. Could any one help me. Find the error below. from pydantic import BaseModel, ValidationError, root_validator Traceback (most recent call last): File "", line 1, in ImportError: cannot import name 'root_validator' from 'pydantic' (C:\Users\Lenovo\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pydantic__init__.py)

I tried in

@validator
def validate_all(cls,v,values,**kwargs):

I am inheriting my pydantic model from some common fields parent model. Values showing only parent class fields, but not my child class fields. for example

class Parent(BaseModel):
    name: str
    comments: str
class Customer(Parent):
    address: str
    phone: str

    @validator
    def validate_all(cls,v,values, **kwargs):
         #here values showing only (name and comment) but not address and phone.
2
if from pydantic import root_validator raises an ImportError, this is most probably because you do not have the right version of pydantic... Which version do you use ?smarie
pydantic==0.32.2samba
Latest is 1.5.1 ... pypi.org/project/pydanticsmarie

2 Answers

5
votes

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

    # If you want to apply the Validator to the fields "name", "comments", "address", "phone"
    @pydantic.validator("name", "comments", "address", "phone")
    @classmethod
    def validate_all_fields_one_by_one(cls, field_value):
        # Do the validation instead of printing
        print(f"{cls}: Field value {field_value}")

        return field_value  # this is the value written to the class field

    # if you want to validate to content of "phone" using the other fields of the Parent and Child class
    @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"] # works because "address" is already validated once we validate "phone"
        # Do the validation instead of printing
        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"]).

3
votes

You need to pass the fields as arguments of the decorator.

class Parent(BaseModel):
    name: str
    comments: str

class Customer(Parent):
    address: str
    phone: str

    @validator("name", "coments", "address", "phone")
    def validate_all(cls, v, values, **kwargs):