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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
from rest_framework import serializersfrom .models import Author, Bookclass BookSerializer(serializers.ModelSerializer):class Meta:model = Bookfields = ['id', 'title', 'isbn', 'published_date']class AuthorSerializer(serializers.ModelSerializer):books = BookSerializer(many=True, read_only=True)book_count = serializers.SerializerMethodField()class Meta:model = Authorfields = ['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