Deploying bulk Django Rest Framework updates instead of updating

I am trying to create a bulk update view for a specific model using the Django Rest Framework. In the short term, only one field needs to be updated (switching the invitation from sent = False to sent = True), but I would like it to be able to provide more functionality in the future. However, when I check the view, a new object is created instead of the current one, which is changing.

I feel that it should be a simple mistake on my part, but I cannot understand what is happening. The serializer object apparently ignores the "id" value passed through JSON, which may contribute to this issue. Current code:

class InviteBulkUpdateView(generics.UpdateAPIView): def get_queryset(self): order = self.kwargs['order'] invite = get_objects_for_user(self.request.user, 'sourcing.view_invite') return invite.filter(order=order) serializer_class = InviteInputSerializer def put(self, request, *args, **kwargs): data = request.DATA serializer = InviteInputSerializer(data=data, many=True) if serializer.is_valid(): serializer.save() return Response(status=status.HTTP_200_OK) else: return Response(status=status.HTTP_400_BAD_REQUEST) class InviteInputSerializer(serializers.ModelSerializer): class Meta: model = Invite fields = ('id', 'order', 'team', 'submitted') 

Can anyone shed some light on what I can do wrong?

+6
source share
2 answers

The obvious thing that appears is that you are not passing instances of objects to your serializer. (This way, it will create new instances, not update.) See documents for working with multiple objects in serializers , where you will see that your QuerySet is passed in.

+4
source

Just in case someone is looking for a library to handle this, I wrote a Django-REST-Framework-bulk , which allows you to do this in several lines (only the example does a bulk update, but the library also allows bulk creation and deletion):

 from rest_framework_bulk import ListCreateBulkUpdateAPIView class FooView(ListCreateBulkUpdateAPIView): model = FooModel 
+7
source

Source: https://habr.com/ru/post/952302/


All Articles