Full answer
Serializers do two jobs in DRF:
- Serialisation: model instance to a dict that renders as JSON (
serializer.data). - 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:
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():
- Each field converts and validates its value (
to_internal_valueand field validators). validate_<field>(self, value)for one-field rules; return the value.validate(self, attrs)for rules across fields; return attrs.- Serializer-level
validatorssuch asUniqueTogetherValidator.
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=Truefor computed or server-set fields andwrite_only=Truefor secrets like passwords. SerializerMethodFieldadds computed output.- Nested serializers are read-only by default; writable nesting needs your own
create()/update(). save(owner=request.user)passes extra values intovalidated_data.- Serializer performance matters: nested serializers on a list can trigger N+1 queries, so pair them with
select_related/prefetch_relatedin the view's queryset.
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