Hvitis
Hvitis

Reputation: 555

DRF ListAPIView custom return not an object

I'm trying to customise ListAPIView in order to return custom object. By default DRF returns object in an array, I want just a customized object.

class PostDetailApiView(ListAPIView, CreateAPIView):
    serializer_class = PostSerializer
    permission_classes = [AllowAny]

    def get_queryset(self, request, *args, **kwargs):
        response = super().get_queryset(request, *args, **kwargs)

        return Response({
                'status': 200,
                'message': 'Post delivered!!',
                'data': response.data
            })

I'm getting error:

lib/python3.7/site-packages/django/template/response.py", line 120, in __iter__
    'The response content must be rendered before it can be iterated over.'
**django.template.response.ContentNotRenderedError: The response content must be rendered before it can be iterated over.**
[03/May/2020 02:34:14] "GET /en-us/blog/api/posts/VueJS%20blog%20in%20progress HTTP/1.1" 500 59

The error dissappears when I return an empty array e.g.:

def get_queryset(self):
    queryset = []
    queryset.append(Post.objects.get(title=self.kwargs["title"]))
    return queryset

How could I return an object like this from Class-based views?:

{
    "status": 200,
    "message": "Post created!",
    "data": {}
}

Thank you

Upvotes: 0

Views: 1129

Answers (1)

Mukul Kumar
Mukul Kumar

Reputation: 2103

# You just need to override your class from APIView class and write your custom response

from rest_framework.views import APIView

class PostDetailApiView(APIView):
    permission_classes = [AllowAny]

    def get(self, request, format=None):
        title = request.data.get("title")
        post = Post.objects.filter(title=title).values('title')

        return Response({
            'status': 200,
            'message': 'Post delivered!!',
            'data': list(post)
        })

Upvotes: 2

Related Questions