Skip to content Skip to sidebar Skip to footer

Django REST Framework Serialization POST Is Slow

I am running on Django 2.1.1 and Python 3.6.5 and am performing a reasonably large POST operation (32,000 JSON objects). I have the following: Model: class Data(models.Model):

Solution 1:

One possible solution is to perform a Django ORM bulk_create() after you validate the data using your serializer. Your view will then look something like this:

class DataView(generics.CreateAPIView):
    def create(self, request, pk, format=None):
        data_serializer = DataSerializer(data=request.data, many=True)
        if data_serializer.is_valid():
            data_objects = []
            for data_object_info in data_serializer.validated_data:
                data_objects.append(Data(**data_object_info))
            Data.objects.bulk_create(data_objects)

or just the following, if you want a one-liner:

Data.objects.bulk_create([Data(**params) for params in data_serializer.validated_data])

If you don't want to clutter your view, then you can write a class or method that performs the validation (using the serializer) and creation. You can then use this inside the view.


Solution 2:

You can try by overriding the create method of serializer as follows:

def create(self, request):
    is_many = True if isinstance(request.data, list) else False

    serializer = self.get_serializer(data=request.data, many=is_many)
    serializer.is_valid(raise_exception=True)
    self.perform_create(serializer)
    headers = self.get_success_headers(serializer.data)
    return Response(serializer.data, status=status.HTTP_201_CREATED,headers=headers)

Post a Comment for "Django REST Framework Serialization POST Is Slow"