Home > Mobile >  How to override the update action in django rest framework ModelViewSet?
How to override the update action in django rest framework ModelViewSet?

Time:09-21

These are the demo models

class Author(models.Model):
    name = models.CharField(max_lenght=5)

class Post(models.Model):
    author = models.ForeignKey(Author, on_delete=models.CASCADE)
    title = models.CharField(max_lenght=50)
    body = models.TextField()

And the respective views are

class AuthorViewSet(viewsets.ModelViewSet):
    queryset = Author.objects.all()
    serializer_class = AuthorSerializer

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

I am trying to perform an update/put action on PostViewSet and which is succesfull, but I am expecting different output. After successful update of Post record, I want to send its Author record as output with AuthorSerializer. How to override this and add this functionality?

CodePudding user response:

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)

CodePudding user response:

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)
  • Related