Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override POST method for bulk adding - Django Rest Framework

I'm writing a REST API using Django Rest Framework and I would like that one of my routes accepts bulk adding on POST method, to create multiple objects. Others methods (GET, PUT, PATCH, DELETE) will still remain the same, accepting only one at a time.

What I have so far is below and it's currently working just fine for posting one at a time.

In my urls.py:

path('book', books.BookViewSet.as_view()),

books.py:

class BookViewSet(viewsets.ModelViewSet):
    serializer_class = BookSerializer
    queryset = Book.objects.all()
    permission_classes = (IsAuthenticated, )

serializer.py:

class BookSerializer(serializers.ModelSerializer):

    def create(self, validated_data):
        # I assume this is the method to be overridden to get this

    class Meta:
        model = Book
        fields = ('id', 'name', 'author_id', 'page_number', 'active')
like image 962
Luc Avatar asked Sep 15 '25 12:09

Luc


1 Answers

Serializer create method, unfortunatelly creates data object by object.You can override create method of ModelViewSet and after validation use bulk_create method.

def create(self, request, *args, **kwargs):
    many = True if isinstance(request.data, list) else False
    serializer = BookSerializer(data=request.data, many=many)
    serializer.is_valid(raise_exception=True)
    author = request.user # you can change here
    book_list = [Book(**data, author=author) for data in serializer.validated_data]
    Book.objects.bulk_create(book_list)
    return Response({}, status=status.HTTP_201_CREATED)
like image 119
kamilyrb Avatar answered Sep 17 '25 01:09

kamilyrb