Django REST Framework Serialization

kelvin benokelvin beno
4 min read

It Begins

If you’re getting started with Django REST Framework (DRF), you’ll keep bumping into something called serialization.
At first, it might sound complicated, but honestly — it’s not. Once you understand what it’s doing, it clicks.

Let’s break it down in simple terms:

  • What serialization actually is

  • Why it matters

  • How you can use it without getting lost

  • Some real-world examples


🔄 So... What is Serialization Anyway?

Imagine you have a bookshelf full of cool books — but you want to share your collection online.
You can’t send a shelf through the internet.
You have to convert it into something simple like a list of titles and authors in a format computers and apps understand — like JSON.

That’s serialization:
Turning complex things (like Django models) into simple data (like JSON).

And the opposite — taking JSON from a user and turning it back into a real Book in your database — that’s deserialization.


✨ Why Should You Even Care?

Because APIs live on serialization.

When your React app (or mobile app, or anything else) asks your Django app for data, it needs it in a nice, clean, readable format (like JSON).
And when someone sends you data (like a form to create a new book), you need to validate it and save it safely.

Serializers handle all that heavy lifting for you.


🔧 Real Example: Serializing a Book

Let’s say you have this model:

models.py
from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=100)
    published_date = models.DateField()

Now, you want to turn your Book objects into JSON easily.
Here’s how you make a serializer:

serializers.py
from rest_framework import serializers
from .models import Book

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

✅ Boom — now DRF knows how to convert Book instances into JSON.


🚀 How to Use the Serializer in a View

Now let's actually send those books out to the world:

views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import Book
from .serializers import BookSerializer

class BookList(APIView):
    def get(self, request):
        books = Book.objects.all()
        serializer = BookSerializer(books, many=True)
        return Response(serializer.data)

So when someone visits your API endpoint, they’ll get a nice JSON list:

jsonCopyEdit[
  {
    "id": 1,
    "title": "Django for APIs",
    "author": "William S. Vincent",
    "published_date": "2020-03-10"
  },
  ...
]

Way easier to work with than raw database objects, right?


🧰 Different Kinds of Serializers

  • ModelSerializer
    This is the quick-and-easy version. DRF looks at your model and figures out the fields automatically.

  • Serializer
    This is the "manual mode" version. You define every field yourself. Great if you need more control.

Here’s a manual serializer:

class BookSerializer(serializers.Serializer):
    title = serializers.CharField()
    author = serializers.CharField()
    published_date = serializers.DateField()

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

    def update(self, instance, validated_data):
        for attr, value in validated_data.items():
            setattr(instance, attr, value)
        instance.save()
        return instance

Most of the time, though, you'll just stick to ModelSerializer unless you need something fancy.


✅ Handling Validation

Serializers don’t just send data out — they also protect your app when new data comes in.

For example, you can make sure a title has the word "django" in it:

def validate_title(self, value):
    if "django" not in value.lower():
        raise serializers.ValidationError("Title must include 'django'")
    return value

This saves you from having to write a ton of manual validation logic elsewhere.


🛠 Read-Only or Write-Only Fields

Sometimes you want to show some data (like id) but never let users change it.
Or accept some input (like a password) but never show it back.

Serializers make that easy:

class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = '__all__'
        read_only_fields = ['id']

🧩 Nesting Serializers

Sometimes your models are related (like a Book belongs to an Author).

You can nest serializers inside each other:

class AuthorSerializer(serializers.ModelSerializer):
    class Meta:
        model = Author
        fields = ['id', 'name']

class BookSerializer(serializers.ModelSerializer):
    author = AuthorSerializer()

    class Meta:
        model = Book
        fields = ['id', 'title', 'author', 'published_date']

Neat, right? You can control exactly how much information you expose.


🏁 Wrapping Up

Serialization sounds fancy, but it's really just "turn my Python stuff into JSON" and "make sure incoming JSON is clean and safe."

Till next time happy coding.

0
Subscribe to my newsletter

Read articles from kelvin beno directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

kelvin beno
kelvin beno

I am a developer from Kenya, passionate about Building software that can shape and change lives for the better