Custom validations for serializer fields Django Rest Framework

why we use validators ?

  • Validators are used to validate the data whether it is semantically valid or not.
  • Validation simplifies the data processing
  • Validation avoids the data redundancy 

Custom Validation for serializer fields

Django REST supports both serializers and model serializers. Serializers provides basic validation for fields, In some cases we need to write custom validations for fields .

Let's take an example for validation for serializer fields.

Case: A company want's recruit for the position of "django developer". Company set age restriction on applicant that his/her age should be greater than twenty and less than thirty years.

Method-1:
 

from datetime import date
from rest_framework import serializers 

def age_restriction(dob):
    today = date.today()
    age = today.year - dob.year - ((today.month, today.day) < (dob.month, dob.day))
    if (not(20 < age < 30)):
        raise serializers.ValidationError("You are no eligible for the job")
    return dob

class EligibilitySerializer(serializers.Serializer):
    email = serializers.EmailField()
    name = serializers.CharField(max_length=200)
    date_of_birth = serializers.DateField(validators=[age_restriction])

"serializers.Serializer" apply primary validations on the field when we call method "is_valid". Serializer converts the value of the field into python object. After it checks for the attribute "validate_<field_name>"  if it has the attribute it will the attribute(method). After this validation it will check for "validators" attribute for the field. validators is list object. so, serializer takes the each validator from the validatiors list and applies it on the field value. After it will call method "validate" and executes validations  init.
"validate_<field_name>" recieves field related value but, where as "validate" method recieves the all fields related data and raises "non field errors"
If any one of the validations[above mentioned validation methods] are failed then validation error will be raised otherwise the valid value will be returned. 

Method - 2:

from datetime import date
from rest_framework import serializers 

class EligibilitySerializer(serializers.Serializer):
    email = serializers.EmailField()
    name = serializers.CharField(max_length=200)
    date_of_birth = serializers.DateField()

    def validate_date_of_birth(self, dob):
        today = date.today()
        age = today.year - dob.year - ((today.month, today.day) < (dob.month, dob.day))
        if (not(20 < age < 30)):
            raise serializers.ValidationError("You are no eligible for the job")
        return dob

Test the above serializer with valid data and invalid data

# testing with valid data
data = {
    'date_of_birth': '1993-04-08',
    'email': 'hello@micropyramid.com',
    'name': 'Micropyramid'
}
s = EligibilitySerializer(data=data)
print(s.is_valid())
# Output: True
print(s.data)
# Output: ReturnDict([('email', 'vidyasagar@micropyramid.com'),
#            ('name', 'Micropyramid'),
#            ('date_of_birth', '1993-14-08')])

# testing with invalid data
data = {
    'date_of_birth': '1980-04-08',
    'email': 'vidyasagar@micropyramid.com',
    'name': 'Micropyramid'
}
print(s.is_valid())
# Output: False
print(s.errors)
# Output: ReturnDict([('date_of_birth', ['You are no eligible for the job'])])

when to use "validate_<field_name>"  and "validators" for fields ?

  • If we are applying a single validator on the field data we have to go for "validate_<field_name>".
  • If we apply more than a single validator then we have to go for "validators".

To Know more about our Django CRM(Customer Relationship Management) Open Source Package. Check Code

    By Posted On
SENIOR DEVELOPER at MICROPYRAMID

Need any Help in your Project?Let's Talk

Latest Comments
Related Articles
Using Django's built in signals and writing custom signals. Divya Sri

Django has a beautiful feature of signals which will record all the actions performed on particular model. In the current blog post we’ll learn how ...

Continue Reading...
How to filter a Django Queryset using Extra Swetha Naretla

Using SQL Queries in Django ORM - Filtering extra objects within in a single query, to reduce the number of queries.

Continue Reading...
Django Subdomains to do advanced things Ashwin Kumar

We always struggle to give users customization's even before they login to the system like abc.micropyramid.com and django don't know how to handle that out ...

Continue Reading...
open source packages

Subscribe To our news letter

Subscribe and Stay Updated about our Webinars, news and articles on Django, Python, Machine Learning, Amazon Web Services, DevOps, Salesforce, ReactJS, AngularJS, React Native.
* We don't provide your email contact details to any third parties