← Back to Django, page 4

django-0078 · Medium mid

How do you handle writable nested serializers in Django REST Framework, and why must create() and update() be written by hand?

DRF supports nested serializers for reading out of the box, but it refuses to save nested data automatically because it cannot know how to create or match the children. For writable nesting, override create() and update(), pop the nested data from validated_data, wrap the work in transaction.atomic(), and decide how updates replace, add or remove children. Often, separate endpoints for children are simpler.

Full answer

Reading is easy: marks = MarkSerializer(many=True, read_only=True). Writing is not. If you pass a writable nested serializer to a ModelSerializer, DRF asserts that the default .create() does not support writable nested fields and tells you to write it explicitly.

Create pattern:

python
def create(self, validated_data):
    marks = validated_data.pop("marks")
    with transaction.atomic():
        student = Student.objects.create(**validated_data)
        Mark.objects.bulk_create([Mark(student=student, **m) for m in marks])
    return student

Update needs decisions that the framework cannot guess:

  • Replace all children (delete and recreate)? Simple, but changes child IDs.
  • Match by ID and update, create the new ones, delete the missing? Requires the child serializer to expose a writable id.
  • Reject changes to children and allow only parent fields?

PATCH makes this harder: if marks is absent, leave children alone; if present, apply your rule.

Practices:

  • Use transaction.atomic() so a failing child does not leave a half-created parent.
  • Validate nested data in the nested serializer (validate_<field>), and cross-check in the parent's validate().
  • Prevent N+1 on reads: prefetch_related("marks") in the queryset.
  • Use bulk_create for children where signals are not needed.
  • Consider flat APIs: POST /students/ then POST /students/1/marks/. They are easier to validate, authorise and document, and avoid large replace-all payloads.
  • For ModelSerializer with many=True nested fields, remember read_only nested fields are ignored on input.
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, transaction
from rest_framework import serializers


class Student(models.Model):
    name = models.CharField(max_length=40)

    class Meta:
        app_label = "school"


class Mark(models.Model):
    student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name="marks")
    subject = models.CharField(max_length=20)
    score = models.IntegerField()

    class Meta:
        app_label = "school"


with connection.schema_editor() as editor:
    for m in (Student, Mark):
        editor.create_model(m)


class MarkSerializer(serializers.ModelSerializer):
    class Meta:
        model = Mark
        fields = ["subject", "score"]


class StudentSerializer(serializers.ModelSerializer):
    marks = MarkSerializer(many=True)

    class Meta:
        model = Student
        fields = ["id", "name", "marks"]

    def create(self, validated_data):
        marks = validated_data.pop("marks")
        with transaction.atomic():
            student = Student.objects.create(**validated_data)
            Mark.objects.bulk_create([Mark(student=student, **m) for m in marks])
        return student

    def update(self, instance, validated_data):
        marks = validated_data.pop("marks", None)
        with transaction.atomic():
            instance.name = validated_data.get("name", instance.name)
            instance.save()
            if marks is not None:                                    # replace-all rule for this API
                instance.marks.all().delete()
                Mark.objects.bulk_create([Mark(student=instance, **m) for m in marks])
        return instance


s = StudentSerializer(data={"name": "Asha", "marks": [{"subject": "Maths", "score": 91}, {"subject": "Science", "score": 84}]})
s.is_valid(raise_exception=True)
student = s.save()
print(StudentSerializer(student).data)

bad = StudentSerializer(data={"name": "Ravi", "marks": [{"subject": "Maths", "score": "x"}]})
print(bad.is_valid(), bad.errors)
print("students after invalid input:", Student.objects.count())

patch = StudentSerializer(student, data={"marks": [{"subject": "Maths", "score": 95}]}, partial=True)
patch.is_valid(raise_exception=True)
patch.save()
print(StudentSerializer(Student.objects.get(pk=student.pk)).data["marks"])

class Naive(serializers.ModelSerializer):
    marks = MarkSerializer(many=True)
    class Meta:
        model = Student
        fields = ["name", "marks"]

try:
    n = Naive(data={"name": "Kiran", "marks": []})
    n.is_valid(raise_exception=True)
    n.save()
except AssertionError as exc:
    print("default create refused:", str(exc)[:55])

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`. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): {'id': 1, 'name': 'Asha', 'marks': [{'subject': 'Maths', 'score': 91}, {'subject': 'Science', 'score': 84}]} False {'marks': {0: {'score': [ErrorDetail(string='A valid integer is required.', code='invalid')]}}} students after invalid input: 1 [{'subject': 'Maths', 'score': 95}] default create refused: The `.create()` method does not support writable nested

Key points

  • Nested reading works; nested writing needs explicit create() and update()
  • Pop nested data from validated_data first
  • Wrap parent and children writes in transaction.atomic()
  • Decide update semantics: replace, upsert or reject
  • Separate endpoints are often simpler

Common mistakes

  • Expecting ModelSerializer to save nested objects automatically
  • Skipping transaction.atomic() and leaving a half-created parent
  • Replacing children on PATCH when the field is absent
  • Causing N+1 queries when reading nested lists

Follow-ups

  • How would you implement upsert of children by ID?
  • When would you prefer separate endpoints for children?
  • How do you validate that a nested list has no duplicates?

Tips

  • Explain why DRF refuses
  • Show the pop-then-create pattern
  • Discuss update semantics