【问题标题】:how to overwrite RetrieveAPIView response django rest framework如何覆盖 RetrieveAPIView 响应 django rest 框架
【发布时间】:2017-09-23 20:51:24
【问题描述】:

我正在从 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'
]

【问题讨论】:

  • 你想改变你的 PostDetailSerializer 序列化数据的方式,而不是你的 View 如何返回它们。此外,您已经发布了您的“本地 url”,127.0.0.1 是您在本地网络中的机器,不是我们可以从其他地方看到或访问的东西。
  • 它只是一个简单的 RetrieveAPIView,我没有实现任何逻辑。 youtube.com/watch?v=_GXGcc7XxvQ。我从这里学习并实现了相同的,但他没有分享如何重写它。

标签: django django-rest-framework


【解决方案1】:

好的,在评论中我打错了电话,你想覆盖你的 View 的 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

【讨论】:

    猜你喜欢
    • 2019-05-23
    • 2018-08-02
    • 1970-01-01
    • 2013-12-23
    • 1970-01-01
    • 2016-05-27
    • 2020-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多