chibisov / drf-extensions

DRF-extensions is a collection of custom extensions for Django REST Framework
http://chibisov.github.io/drf-extensions/docs
MIT License
1.48k stars 208 forks source link

Bulk create #304

Open TJHeeringa opened 3 years ago

TJHeeringa commented 3 years ago

I was looking for a bulk create and a bulk delete option for DRF. I see that in the code there is a bulk create and a bulk update. Would it be possible to add a bulk create too, that uses the validation from a serializer?

I am not sure how this would look like, but I guess it would look something like

class ListCreateModelMixin(BulkOperationBaseMixin):
    def create(self, request, *args, **kwargs):
        if self.is_object_operation():
            return super().create(request, *args, **kwargs)
        else:
            return self.create_bulk(request, *args, **kwargs)

    def create_bulk(self, request, *args, **kwargs):
        is_valid, errors = self.is_valid_bulk_operation()
        if is_valid:
            queryset = self.filter_queryset(self.get_queryset())
            self.pre_create_bulk(queryset)
            serializer = self.get_serializer(data=request.data, many=True)
            serializer.is_valid(raise_exception=True)
            self.perform_bulk_create(serializer)
            self.post_create_bulk(queryset) 
            return Response(status=status.HTTP_204_NO_CONTENT)
        else:
            return Response(errors, status=status.HTTP_400_BAD_REQUEST)

    def perform_bulk_create(self, serializer):
        serializer.save()

    def pre_create_bulk(self, queryset):
        """
        Placeholder method for calling before creating an queryset.
        """
        pass

    def post_create_bulk(self, queryset):
        """
        Placeholder method for calling after creating an queryset.
        """
        pass