0

I am fetching data from RetrieveAPIView I want to overwrite it.

class PostDetailAPIView(RetrieveAPIView):
    queryset = Post.objects.all()
    serializer_class = PostDetailSerializer
    lookup_field = 'slug'

http://127.0.0.1:8000/api/posts/post-python/

it return me result

{
    "id": 2,
    "title": "python",
    "slug": "post-python",
    "content": "content of python"
}

I want to overwrite this with some extra parameters like

[ 
   'result':
   {
    "id": 2,
    "title": "python",
    "slug": "post-python",
    "content": "content of python"
    },
   'message':'success'
]
  • You want to change the way your PostDetailSerializer serializes the data, not how your View returns them. Also, you've posted your "local url", 127.0.0.1 is your machine in your local network, not something we can see or access from elsewhere. – Mateusz Knapczyk Apr 26 '17 at 12:55
  • it just a simple RetrieveAPIView, i didn't implement any logic. https://www.youtube.com/watch?v=_GXGcc7XxvQ. I have learnt from here and implement same but he did not share how to rewrite it. – Sandeep Kumar Apr 26 '17 at 12:58
  • Possible duplicate of [How to return custom JSON in Django REST Framework](http://stackoverflow.com/questions/35019030/how-to-return-custom-json-in-django-rest-framework) – Mateusz Knapczyk Apr 26 '17 at 13:14

2 Answers2

0

you can override the retrieve method. in this way you can send extra data to response.

def retrieve(self, request, *args, **kwargs):
    response = super().retrieve(request, args, kwargs)
    response.data["custom_data"] = "my custom data"
    return response
Mahmudul Hassan
  • 357
  • 3
  • 10
-1

Ok, in comment I made wrong call, you want to overwrite get() method of your View.

class PostDetailAPIView(RetrieveAPIView):
    queryset = Post.objects.all()
    serializer_class = PostDetailSerializer
    lookup_field = 'slug'

    def get(self, request, slug):
        post = self.get_object(slug)
        serializer = PostDetailSerializer(post)
        return Response({
            'result': serializer.data,
            'message': 'success'
        })

Notes 1. I names second argument of get function slug because it's your lookup_field, but it should be name you used in urls. 2. You could instead overwrite retrieve() function 3. This is answer specific for your question, you should also read this answer

Community
  • 1
  • 1
Mateusz Knapczyk
  • 276
  • 1
  • 2
  • 15