Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 39 ยท Serializers

Nested Serializers and Writable Nesting

Embed one serializer inside another in Django REST Framework, serialize related objects and lists, and write nested data by overriding create() and update().

Real data has relationships: an order has lines, a blog post has comments, an author has books. A flat serializer shows only a foreign key number, so a client needs a second request to learn anything about the related object. Nested serializers solve that by embedding the related object's representation inside the parent's.

Reading nested data is easy and works out of the box. Writing it is different: DRF deliberately refuses to guess how to save two objects at once, so you write that code yourself. This lesson shows both sides and the performance trap that comes with nesting.

Reading nested data

Declare the child serializer as a field of the parent. For a one-to-many relation, add many=True, and tell DRF which attribute holds the children with related_name (or source).

Python Nested read: author with books

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The books field reads author.books, the reverse relation created by related_name="books", and renders every book through BookSerializer. An author with no books gets an empty list. Because the field is read_only=True, clients cannot send books while creating an author, which is the safest default.

The other direction: a child with its parent

A foreign key from child to parent is a single object, so no many=True:

Python
class BookDetailSerializer(serializers.ModelSerializer):
    author = AuthorSummarySerializer(read_only=True)

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

Many APIs show a small "summary" serializer for the parent here (id and name only) to avoid dragging the whole parent graph into every child.

If you only need a flat extra value, skip nesting: author_name = serializers.CharField(source="author.name", read_only=True) is cheaper and keeps the output simple.

Controlling depth

Meta.depth is a quick way to auto-nest relations without writing child serializers:

Python
class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = "__all__"
        depth = 1       # expand each foreign key one level, read-only

It is handy for exploration, but you cannot choose which child fields appear, and the nested objects are read-only. For real endpoints, write explicit nested serializers.

Writing nested data

By default DRF raises an assertion if you call .save() with nested data on a ModelSerializer: the default create() cannot know how to build the children. You override create() (and update()) and decide.

Python Create an author and books in one request

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The important points:

  • validated_data["books"] is a list of plain dictionaries, already validated. Pop the nested key before creating the parent, since Author.objects.create(books=...) is not valid.
  • Errors come back nested: the second book's missing title is reported as {'books': [{}, {'title': [...]}]}, with one entry per list item so the client knows which row failed.
  • transaction.atomic makes the writes all-or-nothing. Without it, a failure on the second child leaves the parent and the first child behind.
  • The update policy is yours to choose. The example replaces the list. Real systems often match children by id, update existing ones, create new ones and delete missing ones. DRF cannot choose for you because the right behaviour depends on your business rules.

Replacing children by deleting and re-creating them changes their primary keys. If anything else references a child (orders, comments), match by id instead of delete-and-recreate.

The N+1 query trap

A nested read looks innocent but can fire one extra query per parent. The serializer asks each author for author.books.all(), and each call hits the database. Fix it in the view's queryset with prefetch_related (for reverse and many-to-many relations) or select_related (for forward foreign keys):

Python Counting queries with and without prefetch_related

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Five authors cost six queries without prefetching (one for the authors plus one per author) and two with it. With 1,000 authors the difference is 1,001 queries against two. Whenever a serializer touches a relation, check the queryset that feeds it.

When not to nest

Nesting is a design choice with costs: bigger responses, harder writes and deeper query plans. Consider a flat alternative when the child list can be large (a user with 10,000 orders should get a paginated /users/1/orders/ endpoint, not an embedded list) or when clients rarely need the children. The next lesson shows lighter ways to represent relations: keys, slugs and links.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How do you embed a list of related child objects in a parent serializer?

    Declare a child serializer as a field with many=True; the attribute name must match the relation (related_name) or use source.
  2. 2. Why does saving nested data fail by default?

    DRF refuses to guess; you override create() and update() to define how children are saved.
  3. 3. What is the purpose of transaction.atomic in a nested create()?

    If a child fails, the whole transaction rolls back, so no half-created parent is left behind.
  4. 4. Which fixes the N+1 query problem for a nested list of children?

    prefetch_related loads all children in one extra query. select_related is for forward foreign keys.

Summary

  • Declare a serializer as a field to nest it; use many=True for lists.
  • Nested fields are easiest as read_only=True; writable nesting needs your own create() and update().
  • Pop the nested data from validated_data, create the parent, then the children, inside transaction.atomic.
  • Nested errors are reported per list item.
  • Use prefetch_related and select_related to avoid N+1 queries; prefer flat or separate endpoints for large child lists.

Next: Relational Fields