Search code examples
djangodjango-rest-framework

Django Rest Framework bulk updates inserting instead of updating


I'm trying to build out a bulk update view for a specific model using Django Rest Framework. In the short term, it only needs to update one field (toggling an invite from submitted=False to submitted=True), but I'd like it to be able to provide more functionality in the future. Whenever I test the view, however, a new object is being created instead of the current one being modified.

I feel like this must be a simple mistake on my part, but I can't figure out what's going on. The serializer object appears to be ignoring the value for "id" passed in through JSON, which may be contributing to the issue. Current code is:

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 anybody shed some light onto what I might be doing wrong?


Solution

  • 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.