How to do a PUT (partial update) using generics in Django-Rest-Framework?

前端 未结 2 1731
闹比i
闹比i 2021-01-12 11:51

If I have a class view that looks like this,

class MovieDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Movie.objects.all()
    serializer_cla         


        
相关标签:
2条回答
  • 2021-01-12 11:59

    Or you can just overwrite the get_serializer() method as:

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

    It is especially useful when the front-end guy use the ngResource of the AngularJS to call your API, which only supports the 'put' instead of the 'patch' by default.

    Hope it helps.

    0 讨论(0)
  • 2021-01-12 12:08

    If you are using the DRF route, use PATCH method instead of PUT.

    if you write the urls configuration by yourself, dispatch it to partial_update method in your RetrieveUpdateDestroyAPIView view.

    If you get the serialize by yourself, pass the partial=True to your Serializer

    partial = kwargs.pop('partial', False)
    serializer = self.get_serializer(instance, data=request.data, partial=partial)
    
    0 讨论(0)
提交回复
热议问题