← Back to Django, page 2

django-0028 · Medium mid

In Django REST Framework, what is the difference between Serializer and ModelSerializer, and how does validation work?

A Serializer converts between Python objects and primitive data (JSON) with fields you declare; you write create() and update() yourself. ModelSerializer builds fields from a model and provides default create() and update(). Validation runs field checks, then validate_<field>() methods, then validate() for cross-field rules; call is_valid() before save(), and read serializer.errors when it fails.

Full answer

Serializers do two jobs in DRF:

  1. Serialisation: model instance to a dict that renders as JSON (serializer.data).
  2. Deserialisation: incoming JSON to validated Python data (serializer.validated_data), and optionally to a saved instance.

serializers.Serializer declares every field by hand, like forms.Form. Use it for payloads that do not map to one model, for example a "transfer fee credit" request.

serializers.ModelSerializer reads the model:

python
class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = ["id", "title", "copies"]
        read_only_fields = ["id"]

It infers field types, max_length, required (from blank/default) and unique validators, and gives you create() and update().

Validation order on is_valid():

  1. Each field converts and validates its value (to_internal_value and field validators).
  2. validate_<field>(self, value) for one-field rules; return the value.
  3. validate(self, attrs) for rules across fields; return attrs.
  4. Serializer-level validators such as UniqueTogetherValidator.

is_valid(raise_exception=True) raises ValidationError, which DRF turns into a 400 response.

Practical points:

  • Always list fields; avoid "__all__" in public APIs.
  • Use read_only=True for computed or server-set fields and write_only=True for secrets like passwords.
  • SerializerMethodField adds computed output.
  • Nested serializers are read-only by default; writable nesting needs your own create()/update().
  • save(owner=request.user) passes extra values into validated_data.
  • Serializer performance matters: nested serializers on a list can trigger N+1 queries, so pair them with select_related/prefetch_related in the view's queryset.
python
import sys
import types

import django
from django.conf import settings

# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__

settings.configure(
    SECRET_KEY="demo-only-key-not-for-production",
    ALLOWED_HOSTS=["testserver"],  # the host name used by Django's test client
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "rest_framework", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

from django.db import models, connection
from rest_framework import serializers


class Book(models.Model):
    title = models.CharField(max_length=60)
    copies = models.PositiveIntegerField(default=1)
    shelf = models.CharField(max_length=5)
    class Meta:
        app_label = "school"


with connection.schema_editor() as editor:
    editor.create_model(Book)


class BookSerializer(serializers.ModelSerializer):
    label = serializers.SerializerMethodField()

    class Meta:
        model = Book
        fields = ["id", "title", "copies", "shelf", "label"]
        read_only_fields = ["id"]

    def get_label(self, obj):
        return f"{obj.shelf}/{obj.title}"

    def validate_shelf(self, value):
        if not value[:1].isalpha():
            raise serializers.ValidationError("Shelf must start with a letter, like A1.")
        return value.upper()

    def validate(self, attrs):
        if attrs.get("copies", 1) > 50 and attrs.get("shelf", "").startswith("Z"):
            raise serializers.ValidationError("Shelf Z holds at most 50 copies.")
        return attrs


s = BookSerializer(data={"title": "Swami and Friends", "copies": 3, "shelf": "b2"})
print(s.is_valid(), s.validated_data)
book = s.save()
print(BookSerializer(book).data)

bad = BookSerializer(data={"title": "", "copies": -1, "shelf": "9X"})
print(bad.is_valid())
print({k: [str(e) for e in v] for k, v in bad.errors.items()})

upd = BookSerializer(book, data={"copies": 5}, partial=True)
upd.is_valid(raise_exception=True)
print(upd.save().copies)

Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. Requires `pip install djangorestframework` (run here with DRF 3.16+). Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): True {'title': 'Swami and Friends', 'copies': 3, 'shelf': 'B2'} {'id': 1, 'title': 'Swami and Friends', 'copies': 3, 'shelf': 'B2', 'label': 'B2/Swami and Friends'} False {'title': ['This field may not be blank.'], 'copies': ['Ensure this value is greater than or equal to 0.'], 'shelf': ['Shelf must start with a letter, like A1.']} 5

Key points

  • Serializer = declare fields; ModelSerializer = fields from model + create/update
  • Order: field validation -> validate_<field> -> validate()
  • is_valid() before save(); errors on failure
  • read_only and write_only control direction
  • Nested serializers can cause N+1 queries

Common mistakes

  • Calling serializer.data or save() before is_valid()
  • Using fields = '__all__' and leaking internal fields
  • Forgetting to return the value from validate_<field>()
  • Nesting serializers in list endpoints without prefetching

Follow-ups

  • How do you make a nested serializer writable?
  • Where would you set the request user as owner?
  • How would you return different fields for list and detail views?

Tips

  • Compare with Django forms, the validation flow is similar
  • Name the three validation hooks in order
  • Mention N+1 queries in nested serializers