2017-04-26 52 views
0

我正在從RetrieveAPIView中提取數據我想覆蓋它。如何覆蓋RetrieveAPIView響應django rest框架

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' 
] 
+0

你想改變你的PostDetailSerializer串行數據的方式,您的瀏覽不是如何返回它們。此外,您已發佈「本地網址」,127.0.0.1是您的本地網絡中的機器,而不是我們可以從其他地方看到或訪問的東西。 –

+0

它只是一個簡單的RetrieveAPIView,我沒有實現任何邏輯。 https://www.youtube.com/watch?v=_GXGcc7XxvQ。我已經從這裏學習並實施了,但他沒有分享如何重寫它。 –

+0

[如何在Django REST框架中返回自定義JSON]的可能的重複(http://stackoverflow.com/questions/35019030/how-to-return-custom-json-in-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

相關問題