如何覆盖RetrieveAPIView响应django rest框架

时间:2017-04-26 12:36:36

标签: django django-rest-framework

我从RetrieveAPIView获取数据我想覆盖它。

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

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

它返回结果

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

我想用一些额外的参数来覆盖它,比如

[ 
   'result':
   {
    "id": 2,
    "title": "python",
    "slug": "post-python",
    "content": "content of python"
    },
   'message':'success'
]

1 个答案:

答案 0 :(得分:-1)

好的,在评论中我拨打错误电话,您想要覆盖视图的get()方法。

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'
        })

备注 1.我命名get函数slug的第二个参数,因为它是您的lookup_field,但它应该是您在url中使用的名称。 2.您可以改为覆盖retrieve()功能 3.这是针对您的问题的答案,您还应该阅读this answer