Bulk creation of a resource with Django Rest Framework

Django REST framework is a powerful and flexible toolkit for building Web APIs.
Bulk creation in an app or API allow us to create many object in one request.
The first step is to install and setup django rest framework.
Assuming you’re using pip:
pip install djangorestframework
We need to add rest_framework to INSTALLED_APPS in settings.py:
# settings.pyINSTALLED_APPS = [
...
'rest_framework',
]
And add the following to your root urls.py
file.
# urls.pyurlpatterns = [
...
path('api-auth/', include('rest_framework.urls'))
]
Now let’s take a look at the model we’re going to use.
# models.pyfrom django.db import models
class Client(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
contact = models.CharField(max_length=30)
email = models.EmailField(unique=True)
address = models.CharField(max_length=30)
We will create a serializer for this model using Django REST’s ModelSerializer helper class:
# serializers.pyfrom myapp.models import Client
from rest_framework import serializers
class ClientSerializer(serializers.ModelSerializer):
class Meta:
model = Client
fields = ['id', 'first_name', 'last_name', 'contact',
'email', 'address']
Next we need to create a mixin that will allow the view to handle an array of JSON objects in the request so that the actual view can process and create new objects in a bulk fashion:
# mixins.pyclass CreateListMixin:
"""Allows bulk creation of a resource."""
def get_serializer(self, *args, **kwargs):
if isinstance(kwargs.get('data', {}), list):
kwargs['many'] = True
return super().get_serializer(*args, **kwargs)
We can now create a view and make it use the mixin.
# viewsets.pyfrom rest_framework import viewsets
from myapp.serializers import ClientSerializer
from myapp.mixins import CreateListMixin
from myapp.models import Client
class ClientViewSet(CreateListMixin, viewsets.ModelViewSet):
queryset = Client.objects.all()
serializer_class = ClientSerializer
The last step is to set a URL to make the request to.
# urls.pyfrom django.conf.urls import url, include
from rest_framework import routers
from views import ClientViewSet
router = routers.DefaultRouter()
router.register(r'clients', ClientViewSet)
And it do the trick!