简体   繁体   中英

How to validate more than one field of pydantic model

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.

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):

First off, if you are having an error importing root_validator , I would update pydantic.

pip install -U pydantic

A lot of the examples above show you how to use the same validator on multiple values one at a time. Or they add a lot of unnecessary complexity to accomplish what you want. You can simply use the following code to validate multiple fields at the same time in the same validator using the root_validator decorator.:

from pydantic import root_validator
from pydantic import BaseModel

class Parent(BaseModel):
    name: str = "Peter"
    comments: str = "Pydantic User"

class Customer(Parent):
    address: str = "Home"
    phone: str = "117"

    @root_validator
    def validate_all(cls, values):
         print(f"{values}")
         values["phone"] = "111-111-1111"
         values["address"] = "1111 Pydantic Lane"
         print(f"{values}")
         return values

Output:

{'name': 'Peter', 'comments': 'Pydantic User', 'address': 'Home', 'phone': '117'}

{'name': 'Peter', 'comments': 'Pydantic User', 'address': '1111 Pydantic Lane', 'phone': '111-111-1111'}

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" (eg "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 (eg values["comments"] ).

This example contains all the necessary information to answer your question.

    class User(BaseModel):
        name: Optional[str] = ""

        class Config:
            validate_assignment = True

        @validator("name")
            def set_name(cls, name):
            return name or "foo"

As per the documentation , "a single validator can be applied to multiple fields by passing it multiple field names" (and "can also be called on all fields by passing the special value '*' "). Thus, you could add the fields you wish to validate to the validator decorator, and using field.name attribute you can check which one to validate each time the validator is called. If a field does not pass the validation, you could raise ValueError , "which will be caught and used to populate ValidationError " (see "Note" section here ). If you need to validate a field based on other field(s), you have to check first if they have already been validated using values.get() method, as shown in this answer (Update 2) . The below demonstrates an example, where fields such as name , country_code , and phone number (based on the provided country_code ) are validated. The regex patterns provided are just examples for the purposes of this demo, and are based on this and this answer..

from pydantic import BaseModel, validator
import re

name_pattern = re.compile(r'[a-zA-Z\s]+$')
country_codes = {"uk", "us"}
UK_phone_pattern = re.compile(r'^(\+44\s?7\d{3}|\(?07\d{3}\)?)\s?\d{3}\s?\d{3}$')  # UK mobile phone number. Valid example: +44 7222 555 555
US_phone_pattern = re.compile(r'^(\([0-9]{3}\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}$')  # US phone number. Valid example: (123) 123-1234
phone_patterns = {"uk": UK_phone_pattern, "us": US_phone_pattern}

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

    @validator("name", "country_code", "phone")
    def validate_atts(cls, v, values, field):
        if field.name == "name":
            if not name_pattern.match(v): raise ValueError(f'{v}" is not a valid name.')
        elif field.name == "country_code":
             if not v.lower() in country_codes: raise ValueError(f'{v} is not a valid country code.')
        elif field.name == "phone" and values.get('country_code'):
            c_code = values.get('country_code').lower()
            if not phone_patterns[c_code].match(v): raise ValueError(f'{v} is not a valid phone number.')
        return v

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM