[Solved]-Django Rest Framework bulk updates inserting instead of updating

7👍

You’re not passing object instances to your serializer. (Thus it will create new instances rather than update.) See the docs on dealing with multiple objects in serializers where you’ll see your QuerySet passed in.

11👍

Just in case somebody is looking for a library to handle this, I wrote a Django-REST-Framework-bulk which allows to do that in a couple of lines (the example only does bulk update but the library also allows bulk create and delete):

from rest_framework_bulk import ListCreateBulkUpdateAPIView

class FooView(ListCreateBulkUpdateAPIView):
    model = FooModel

-1👍

Django has update method to handle that. You may want to read full info from django documentation.

Here is a sample code where you can use to update given field for multiple records:

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.exceptions import APIException

class Room_Update_ViewSet(APIView):
    def put(self, request,*args, **kwargs):
        hotel_id = self.kwargs.get('hotel_id')
        room_ids = self.request.query_params.get('room_ids')
        room_ids = list(map(int, room_ids.split(',')))
        try:
            Room.objects.filter(hotel_id=hotel_id,id__in=room_ids).update(booked_status=False)
            instances = Room.objects.filter(hotel_id=hotel_id,id__in=room_ids)
            serializer = RoomSerializer(instance=instances, many=True)
            return Response(serializer.data,status=status.HTTP_200_OK)
        except Exception as e:
            print("Error udating rooms-->",e)
            raise APIException
👤7guyo

Leave a comment