How to PATCH a single field using Django Rest Framework?

后端 未结 5 1867
逝去的感伤
逝去的感伤 2020-12-23 12:31

I have a model \'MyModel\' with many fields and I would like to update a field \'status\' using PATCH method. I\'m using class based views. Is there any way to implement PAT

5条回答
  •  情深已故
    2020-12-23 13:11

    I struggled with this one for a while, but it is a very straightforward implementation using generic views or a combination of generic views and mixins.

    In the case of using a generic update view (generics.UpdateAPIView), just use the following code, making sure the request type is PATCH:

    class UpdateUser(generics.UpdateAPIView):
    
        queryset = User.objects.all()
        serializer_class = UserSerializer
    

    There's nothing else to it!

    If you're using an update mixin (mixins.UpdateModelMixin) in combination with a generic view (generics.GenericAPIView), use the following code, making sure the request type is PATCH:

    class ActivateUser(mixins.UpdateModelMixin, generics.GenericAPIView):
    
        serializer_class = UserSerializer
        model = User
        lookup_field = 'email'
    
        def get_queryset(self):
            queryset = self.model.objects.filter(active=False)
            return queryset
    
        def patch(self, request, *args, **kwargs):
            return self.partial_update(request, *args, **kwargs)
    

    The second example is more complex, showing you how to override the queryset and lookup field, but the code you should pay attention to is the patch function.

提交回复
热议问题