← Back to Django Course | Chapter 14: REST API with DRF | Lesson 3 of 6

Serializers Basics

A serializer is a translator that turns a Django model into JSON, and turns incoming JSON back into a model.

Why Serializers Are Needed

A QuerySet of Book objects can't be sent over HTTP directly — it needs to become JSON text first. A serializer defines exactly how each model field maps to a JSON field, and validates data coming back in.

Example: Why Serializers Are Needed

A QuerySet of Book objects can't be sent over HTTP directly — it needs to become JSON text first. A serializer defines exactly how each model field maps to a JSON field, and validates data coming back in.

markup
# Python object (a Book instance) --> serializer --> JSON text
# {'id': 1, 'title': 'Dune', 'author': 'Frank Herbert', 'published_year': 1965}
{# Django-only code -- models.py/views.py/urls.py/settings.py snippets, or template markup using Django template tags/variables -- can't run standalone via Judge0 or the browser preview, since it needs a real Django project. Only this course's pure-Python examples (example_lang == 'python', no Django imports) are actually runnable, so those still get the button below. #}

Creating a ModelSerializer

ModelSerializer is the DRF equivalent of ModelForm: it inspects a model and builds matching serializer fields automatically, based on the fields you list.

Example: Creating a ModelSerializer

ModelSerializer is the DRF equivalent of ModelForm: it inspects a model and builds matching serializer fields automatically, based on the fields you list.

markup
from rest_framework import serializers
from .models import Book

class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = ['id', 'title', 'author', 'published_year']
{# Django-only code -- models.py/views.py/urls.py/settings.py snippets, or template markup using Django template tags/variables -- can't run standalone via Judge0 or the browser preview, since it needs a real Django project. Only this course's pure-Python examples (example_lang == 'python', no Django imports) are actually runnable, so those still get the button below. #}

Serializing a Queryset

Pass a queryset with many=True to serialize multiple objects at once, then access .data to get plain Python data ready for a JSON response.

Example: Serializing a Queryset

Pass a queryset with many=True to serialize multiple objects at once, then access .data to get plain Python data ready for a JSON response.

bash
books = Book.objects.all()
serializer = BookSerializer(books, many=True)
print(serializer.data)
# [OrderedDict([('id', 1), ('title', 'Dune'), ('author', 'Frank Herbert'), ('published_year', 1965)])]

⚠️ Run this command in your terminal.

Validating Incoming Data

When building a serializer from raw input data, call is_valid() before reading .data or .validated_data — this runs field-level validation like a ModelForm does.

Warning: Reading serializer.data before calling is_valid() raises an error, since DRF doesn't know yet whether the data is valid.

Example: Validating Incoming Data

When building a serializer from raw input data, call is_valid() before reading .data or .validated_data — this runs field-level validation like a ModelForm does.

markup
serializer = BookSerializer(data={'title': 'Dune', 'author': 'Frank Herbert', 'published_year': 1965})
if serializer.is_valid():
    book = serializer.save()
else:
    print(serializer.errors)
{# Django-only code -- models.py/views.py/urls.py/settings.py snippets, or template markup using Django template tags/variables -- can't run standalone via Judge0 or the browser preview, since it needs a real Django project. Only this course's pure-Python examples (example_lang == 'python', no Django imports) are actually runnable, so those still get the button below. #}
Common Mistakes
  1. Listing a field in the serializer's Meta.fields that doesn't exist on the model, causing a runtime error.
  2. Forgetting that ModelSerializer's default fields are read-write, so sensitive fields (like an internal id used elsewhere) may be exposed unintentionally unless explicitly excluded.
  3. Calling serializer.data before calling is_valid() on a serializer built from incoming request data, which raises an AssertionError.
Chapter Summary
  • A serializer converts Django model instances to JSON (serialization) and validates incoming JSON back into Python data (deserialization).
  • ModelSerializer automatically generates fields based on a model, similar to how ModelForm generates form fields.
  • Meta.fields controls exactly which model fields are exposed through the API.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.