[Django]-How to override the update action in django rest framework ModelViewSet?

2👍

I figured out some less code fix for my issue.

class PostViewSet(viewsets.ModelViewSet):
    queryset = Post.objects.all()
    serializer_class = PostStatSerializer

    def update(self, request, *args, **kwargs):
        super().update(request, *args, **kwargs)
        instance = self.get_object()
        return Response(AuthorSerializer(instance.author).data)

3👍

You can override update method for this:

class PostViewSet(viewsets.ModelViewSet):
    queryset = Post.objects.all()
    serializer_class = PostStatSerializer

    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)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)

        # this will return autor's data as a response 
        return Response(AuthorSerializer(instance.parent).data)

Leave a comment