Nested Serializer and Deserializer in Django Rest Framework with Examples

Nested serializers and deserializers are powerful features in Django Rest Framework (DRF) that allow you to work with complex data structures in your API. They are particularly useful when dealing with relationships between models or when you need to include related data in your API responses. In this blog, we’ll explore the concept of nested serializers and deserializers in DRF with practical examples.

Read our blog, if you dont know How to Serializer and Deserializer in Django Rest Framework with Examples

Understanding Nested Serializers

Nested serializers in DRF refer to the practice of including one serializer within another. This is commonly used when dealing with related models in Django. By nesting serializers, you can represent the hierarchical structure of your data, making it easier to work with complex API responses.

Example: Serializing Nested Data

Suppose you have two Django models: Author and Book, with a foreign key relationship between them. Each book is associated with an author.

# models.py

from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=100)

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.ForeignKey(Author, on_delete=models.CASCADE)

To serialize this data with nested serializers, create separate serializers for both models:

# serializers.py

from rest_framework import serializers
from .models import Author, Book

class AuthorSerializer(serializers.ModelSerializer):
    class Meta:
        model = Author
        fields = '__all__'

class BookSerializer(serializers.ModelSerializer):
    author = AuthorSerializer()  # Nest AuthorSerializer

    class Meta:
        model = Book
        fields = '__all__'

Now, when you serialize a Book instance, the author field will contain serialized author data within the JSON response

Example: Deserializing Nested Data

When deserializing data… with nested serializers, you can nest data accordingly in your input JSON.

Suppose you want to create a new book instance with its associated author. You can use nested data like this:

{
    "title": "The Hobbit",
    "author": {
        "name": "J.R.R. Tolkien"
    }
}

To handle this nested data during deserialization, ensure that your BookSerializer is designed to handle nested author data as well:

# serializers.py

class BookSerializer(serializers.ModelSerializer):
    author = AuthorSerializer()  # Nest AuthorSerializer

    class Meta:
        model = Book
        fields = '__all__'

    def create(self, validated_data):
        author_data = validated_data.pop('author')
        author, created = Author.objects.get_or_create(**author_data)
        book = Book.objects.create(author=author, **validated_data)
        return book

In this example, we override the create method of the BookSerializer to handle nested author data correctly. It creates a new Author instance or retrieves an existing one based on the provided author data.

Conclusion

Nested serializers and deserializers in Django Rest Framework allow you to work with complex data structures and relationships in your API. By nesting serializers, you can represent the hierarchical nature of your data, making it easier to serialize and deserialize related data models. This feature is invaluable when dealing with complex APIs that involve multiple models with relationships

Blogs You Might Like to Read!