How to PATCH a single field using Django Rest Framework?

后端 未结 5 1866
逝去的感伤
逝去的感伤 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:29

    As Kevin Brown stated you could use the partial=True, which chefarov clarified nicely.

    I would just like to correct them and say you could use generics freely, depending on the HTTP method you are using:

    • If you are using PATCH HTTP method like asked, you get it out of the box. You can see UpdateModelMixin code for partial_update:

      def partial_update(self, request, *args, **kwargs):
          kwargs['partial'] = True
          return self.update(request, *args, **kwargs)
      
    • For any HTTP method different from PATCH, this can be accomplished by just overriding the get_serializer method as follows:

      def get_serializer(self, *args, **kwargs):
          kwargs['partial'] = True
          return super(YOUR_CLASS, self).get_serializer(*args, **kwargs)
      

    This will create the serializer as partial, and the rest of the generics will work like a charm without any manual intervention in the update/partial_update mechanism.

    Under the hood

    I used the generic: generics.UpdateAPIView which uses the UpdateModelMixin which has this code:

    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        …
    

    So, if you override the get_serializer function, you can actually override the partial argument and force it to be true.

    Please note, that if you want it partial only for some of the HTTP methods, this makes this approach more difficult.

    I am using djangorestframework==3.5.3

提交回复
热议问题