Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 491
user2708386 Avatar asked Aug 22 '13 17:08

user2708386


1 Answers

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
like image 168
miki725 Avatar answered Oct 13 '22 00:10

miki725