Three ways to Validate data in Django Serializers

Photo by Chris Ried on Unsplash

Three ways to Validate data in Django Serializers

Django rest framework

Introduction

Validation is a major aspect when building Django projects as it ensures the data inputted are accurate and clear. it also helps to mitigate project defects and removes any outliers or redundancy in our project. In Django Rest Framework, data validation is mainly done in the serializer. The serializer allows complex datatypes or model instances to be converted to python datatypes that can be easily rendered as JSON on the browser. In this article, I will be showing you three ways to validate data in Django Serializers.

Setting up the environment and Project

Create a new virtual environment, activate it, and go to your project directory

python -m venv env
./env/Scripts/activate

Install Django and Django rest framework

pip install django
pip install djangorestframework

create a new project

django-admin startproject new

Run the server to ensure the project runs properly

python manage.py runserver

create a new app

python manage.py startapp bookstore

After creating our App, we will need to add the <app name> and rest_framework to installed apps in new/settings.py

INSTALLED_APPS = [
             .......
             'bookstore',
             'rest_framework',
]

our App is set, let's dive into creating the models.

Creating Models

I will be building a model for the bookstore App

from django.db import models

class Book(models.Model):
        title = models.CharField(max_length=100)
        author = models.CharField(max_length=100)
        year_published = models.IntegerField()
        description = models.TextField(max_length=250)

         def __str__(self):
            return self.title

Let's migrate our model to the database

python manage.py makemigrations
python manage.py migrate

Creating serializer

from .models import Book #Imports my model
from rest_framework import serializers

class BookSerializer(serializers.ModelSerializer):
      class Meta:
             model = Book
             fields = ['id', 'title', 'author', 'year_publised', 'description']

Assuming the model is only valid if the year_published is greater than 2000, and the length of the title's name is greater than the author's name. Let's validate these in three ways.

1. Field validation

This allows us to validate a specific field in our serializer. It is done by defining a method in our serializer that is written in the format validate_<fieldname>. The method takes a parameter which is the value of the field.

Example:

from .models import Book #Imports my model
from rest_framework import serializers

class BookSerializer(serializers.ModelSerializer):
    class Meta:
         model = Book
         fields = ['id', 'title', 'author', 'year_publised', 'description']

    def validate_year_published(self, value):
          if value < 2000:
             return serializers.ValidationError(
                "The year_published has to be greater than 2000"
                )
          return value

2. Object-level Validation

In a situation where we have to compare two fields in our serializer, this method is the one to use. it is done by defining a validate method in our serializer. The method takes a parameter which is the field: value dictionary.

Example:

from .models import Book #Imports my model
from rest_framework import serializers

class BookSerializer(serializers.ModelSerializer):
    class Meta:
         model = Book
         fields = ['id', 'title', 'author', 'year_publised', 'description']

    def validate(self, data):
       if len(data['title']) > len(data['author']):
           return data
       return serializers.ValidationError(
                  "The length of the author cannot be greater than the title"
                           )

3. Functional Validation

If we are going to be validating a particular field in multiple serializers, this approach is the best to avoid writing the same code over and over again. It involves defining a function outside a serializer and passing it as an argument in the serializer field.

Example:

from .models import Book #Imports my model
from rest_framework import serializers

def is_year_published(value):
   if value <  2000:
        return serializers.ValidationError("Year cannot be less than 2000")
   return value

class BookSerializer(serializers.ModelSerializer):
    year_published = serializers.IntegerField(validators=[is_year_published])
    class Meta:
         model = Book
         fields = ['id', 'title', 'author', 'year_publised', 'description']

Conclusion

You have learned three ways to validate data in Django rest framework serializers, I hope this helps as you write better code.

Don't forget to follow me for more python and Django-related content.

Did you find this article valuable?

Support Ubaydah's Blog🎉 by becoming a sponsor. Any amount is appreciated!