Working with multiple serializers
This blog describes various ways to work with multiple serializers and multiple objects in the same view, using Django and Django REST Framework
My major work in Week 5 of the GSoC Coding Phase involved working with multiple serializers in the same view. Many times, we need a queryset
which includes objects from differents models, or a combination of different serializers.
List Serializers
Usually, we use POST
requests to create a single object, and very rarely do we create a list of them. So if it’s a single model
where we are creating a list of objects, bulk_create()
would be useful in this case.
To get a REST API, we will need to serialize the JSON Response. Here’s when list serializers will come into use.
Another option would be to do the following in the views.py
:
objs = Book.objects.bulk_create(results)
serializer = BookSerializer(objs, many=True)
results
will be a list of the objects to be created.
TIP: You cannot use bulk_create()
on inherited models. It creates a discrepancy in the id
so it is not allowed.
Separating different lists
We can create a combination of querysets from different models in a single API.
books
and authors
would be 2 separate lists containing respective data. We can extend this method to any number of serializer we want.
Combining different serializers into a single list
Now we do not want separate lists for different queryset, but an overall queryset for this purpose. Do something similar to this in your views.py
:
results = []books = Books.objects.all()
authors = Author.objects.all()
results.append(BookSerializer(books, many=True).data)
results.append(AuthorSerializer(authors, many=True).data)return Response(results, status=status.HTTP_200_OK)
You define an empty list and go on appending objects to the list. Finally, you can return the list in your Response
. You can use it within loops, or with conditional statements.
References
Have a look at the documentation for multiple create and multiple update for more details.