
Django Rest Framework (DRF) allows you to use serializers to convert complex data types, such as Django models, into Python data types that can then be easily rendered into JSON or other content types. You can use serializers in a nested manner to handle more complex relationships between models.
For example, if you have two models, Author
and Book
, where an Author
can have multiple Books
, you could define the following serializers:
from rest_framework import serializers
from .models import Author, Book
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = '__all__'
class AuthorSerializer(serializers.ModelSerializer):
books = BookSerializer(many=True)
class Meta:
model = Author
fields = '__all__'
In this example, the AuthorSerializer
uses the BookSerializer
to represent the books
field, which is a many-to-one relationship between the Author
and Book
models. The many=True
argument indicates that there can be multiple Books
related to a single Author
.
You can then use these serializers in your views to retrieve or update data for the related models. For example:
from rest_framework import generics
class AuthorList(generics.ListCreateAPIView):
queryset = Author.objects.all()
serializer_class = AuthorSerializer
class AuthorDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Author.objects.all()
serializer_class = AuthorSerializer
This example defines two views, AuthorList
and AuthorDetail
, which allow you to retrieve a list of authors or retrieve a single author, respectively. The serializer_class
attribute is used to specify which serializer should be used to represent the data in the response.
A simple project that demonstrates how to use nested serializers in Django Rest Framework.
1. First, create a new Django project and app:
django-admin startproject nested_serializers
cd nested_serializers
django-admin startapp books
2. Next, add the necessary dependencies to your nested_serializers/settings.py
file:
INSTALLED_APPS = [
# ...
'rest_framework',
'books',
]
3. Create the Author
and Book
models in books/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)
4. Create the serializers in books/serializers.py
:
from rest_framework import serializers
from .models import Author, Book
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = '__all__'
class AuthorSerializer(serializers.ModelSerializer):
books = BookSerializer(many=True)
class Meta:
model = Author
fields = '__all__'
5. Create the views in books/views.py
:
from rest_framework import generics
from .models import Author
from .serializers import AuthorSerializer
class AuthorList(generics.ListCreateAPIView):
queryset = Author.objects.all()
serializer_class = AuthorSerializer
class AuthorDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Author.objects.all()
serializer_class = AuthorSerializer
6. Finally, add the URLs in nested_serializers/urls.py
:
from django.urls import path, include
from books.views import AuthorList, AuthorDetail
urlpatterns = [
path('authors/', AuthorList.as_view(), name='author-list'),
path('authors/<int:pk>/', AuthorDetail.as_view(), name='author-detail'),
]
7. Run the migrations to create the database tables:
python manage.py makemigrations
python manage.py migrate
8. Start the development server:
python manage.py runserver
You can now access the API at http://localhost:8000/authors/
to view a list of authors and their related books. You can also access a single author at http://localhost:8000/authors/<id>/
.