Instagram
youtube
Facebook
Twitter

Validation in Django REST Framework

In this tutorial, we will explore how to implement validation in Django REST Framework. We are using the Students model and the StudentsSerializer from our previous tutorial.

We will cover both field-level validation and object-level validation to ensure that the data meets certain criteria before it's processed.

Validation in Django REST Framework

  • Validation is an essential aspect of building reliable and consistent APIs.

  • It ensures that the data input adheres to specific rules and constraints before being saved to the database.

  • In the context of DRF, validation is performed using serializers to verify the correctness of the incoming data.

There are mainly two types of validations in Django REST Framework.

1. Field-Level Validation:

Field-level validation involves checking the validity of individual fields. Let's say we want to ensure that the roll number is positive for all students. We can achieve this by adding field-level validation to the serializer.

Code:

from rest_framework import serializers
from .models import Students

class StudentsSerializer(serializers.ModelSerializer):
    class Meta:
        model = Students
        fields = '__all__'

    def validate_Roll(self, value):
        if value <= 0:
            raise serializers.ValidationError(f"{value} Roll number must be a positive integer.")
        return value

Result:

2. Object-Level Validation:

Object-level validation is used when the validation depends on multiple fields. For example, let's say we want to ensure that the roll number is unique for each student. We can achieve this through object-level validation.

Code:

from rest_framework import serializers
from .models import Students

class StudentsSerializer(serializers.ModelSerializer):
    class Meta:
        model = Students
        fields = '__all__'

    def validate(self, data):
        roll = data.get('Roll')
        if Students.objects.filter(Roll=roll).exists():
            raise serializers.ValidationError("A student with this roll number already exists.")
        return data

Result: