Serializers in Django REST Framework

Serializers are one of the most important components of Django REST Framework (DRF). They convert complex data types such as Django model instances and querysets into JSON format, making them easy to send over an API. They also validate incoming data before saving it to the database.

In simple terms, serializers act as a bridge between Django models and JSON data.

Why Do We Need Serializers?

Consider a Django model:

from django.db import models

class Employee(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField()
    department = models.CharField(max_length=100)

    def __str__(self):
        return self.name

If we retrieve an employee object, Django cannot directly convert it into JSON. Serializers solve this problem by transforming model data into JSON and validating incoming requests.

Creating a Basic Serializer

Create a file named serializers.py inside your app:

from rest_framework import serializers

class EmployeeSerializer(serializers.Serializer):
    id = serializers.IntegerField(read_only=True)
    name = serializers.CharField(max_length=100)
    email = serializers.EmailField()
    department = serializers.CharField(max_length=100)

Here, each serializer field corresponds to a model field.

Serializing Data

Convert a Python object into JSON-friendly data:

from .serializers import EmployeeSerializer

employee = {
    "id": 1,
    "name": "Tarun Kumar",
    "email": "tarun@example.com",
    "department": "IT"
}

serializer = EmployeeSerializer(employee)

print(serializer.data)

Output:

{
    "id": 1,
    "name": "Tarun Kumar",
    "email": "tarun@example.com",
    "department": "IT"
}

Deserializing Data

Convert incoming JSON data into Python objects:

data = {
    "name": "Tarun Kumar",
    "email": "tarun@example.com",
    "department": "IT"
}

serializer = EmployeeSerializer(data=data)

if serializer.is_valid():
    print(serializer.validated_data)

Output:

{
    'name': 'Tarun Kumar',
    'email': 'tarun@example.com',
    'department': 'IT'
}

Validating Data

DRF serializers automatically validate data.

Example:

data = {
    "name": "Tarun Kumar",
    "email": "invalid-email",
    "department": "IT"
}

serializer = EmployeeSerializer(data=data)

if not serializer.is_valid():
    print(serializer.errors)

Output:

{
    "email": [
        "Enter a valid email address."
    ]
}

Using Serializers in APIView

from rest_framework.views import APIView
from rest_framework.response import Response
from .serializers import EmployeeSerializer

class EmployeeAPIView(APIView):

    def get(self, request):
        employee = {
            "id": 1,
            "name": "Tarun Kumar",
            "email": "tarun@example.com",
            "department": "IT"
        }

        serializer = EmployeeSerializer(employee)

        return Response(serializer.data)

Response:

{
    "id": 1,
    "name": "Tarun Kumar",
    "email": "tarun@example.com",
    "department": "IT"
}

Serializing Multiple Objects

When working with lists or querysets, use many=True.

employees = [
    {
        "id": 1,
        "name": "John",
        "email": "john@example.com",
        "department": "HR"
    },
    {
        "id": 2,
        "name": "Tarun",
        "email": "tarun@example.com",
        "department": "IT"
    }
]

serializer = EmployeeSerializer(employees, many=True)

print(serializer.data)

Output:

[
    {
        "id": 1,
        "name": "John",
        "email": "john@example.com",
        "department": "HR"
    },
    {
        "id": 2,
        "name": "Tarun",
        "email": "tarun@example.com",
        "department": "IT"
    }
]

Saving Data with Serializers

To save data, implement create() and update() methods.

from rest_framework import serializers
from .models import Employee

class EmployeeSerializer(serializers.Serializer):
    id = serializers.IntegerField(read_only=True)
    name = serializers.CharField(max_length=100)
    email = serializers.EmailField()
    department = serializers.CharField(max_length=100)

    def create(self, validated_data):
        return Employee.objects.create(**validated_data)

    def update(self, instance, validated_data):
        instance.name = validated_data.get('name', instance.name)
        instance.email = validated_data.get('email', instance.email)
        instance.department = validated_data.get('department', instance.department)
        instance.save()
        return instance

Common Serializer Field Types

Field TypeDescription
CharFieldText data
IntegerFieldInteger values
FloatFieldDecimal values
BooleanFieldTrue/False values
EmailFieldEmail validation
DateFieldDate values
DateTimeFieldDate and time values
URLFieldURL validation

Benefits of Serializers

  • Convert model instances into JSON
  • Validate incoming data
  • Simplify API development
  • Handle nested relationships
  • Support custom validation rules

Conclusion

Serializers are the backbone of Django REST Framework. They transform data between Django models and JSON while providing powerful validation features. Understanding serializers is essential before moving on to ModelSerializer and advanced API development.