0 day streak
python / intermediate
Snippet

Django Model Serializer with Nested Relationships

Django REST Framework serializers handle complex data transformations between Django models and JSON. This example shows nested serializers where an Author's serialized data includes their related Books and a computed book count field.

snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
from rest_framework import serializers
from .models import Author, Book
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = ['id', 'title', 'isbn', 'published_date']
class AuthorSerializer(serializers.ModelSerializer):
books = BookSerializer(many=True, read_only=True)
book_count = serializers.SerializerMethodField()
class Meta:
model = Author
fields = ['id', 'name', 'email', 'books', 'book_count']
def get_book_count(self, obj):
return obj.books.count()
django
Breakdown
1
BookSerializer(serializers.ModelSerializer)
ModelSerializer automatically generates fields based on the model definition
2
books = BookSerializer(many=True, read_only=True)
The many=True parameter indicates a one-to-many relationship, read_only avoids requiring books in input
3
SerializerMethodField()
Custom field that calls a method to compute its value dynamically
4
def get_book_count(self, obj):
Method receives the Author instance and returns computed book count