[Fixed]-Overriding Django REST ViewSet with custom post method and model

17๐Ÿ‘

I figured it out. For those looking for an answer as well, the solution was to explicitly define the actions that occur when request.method == 'POST' and pass a the object into the serializer.

    @detail_route(methods=['post','get'])
    def comment(self, request, **kwargs):

        user = self.get_object()

        self.queryset = Comment.objects.filter(recipient=user.id)
        self.serializer_class = CommentFlat

        if request.method == 'POST':

            # request.data is from the POST object. We want to take these
            # values and supplement it with the user.id that's defined
            # in our URL parameter
            data = {
                'comment': request.data['comment'],
                'rating': request.data['rating'],
                'author': request.data['author'],
                'recipient': user.id
            }

            serializer = CommentFlat(data=data)

            if serializer.is_valid():
                serializer.save()
                return Response(serializer.data, status=status.HTTP_201_CREATED)
            else:
                return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

        # Return GET by default
        else:

            serializer = CommentFlat(instance=self.queryset, many=True)

            return Response(serializer.data)
๐Ÿ‘คuser2989731

Leave a comment