Search code examples
pythondjangodjango-rest-frameworkdjango-viewsdjango-serializer

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


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?


Solution

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