2016-08-22 83 views
1

我有一個模型Foo,我用它作爲我的香草DRF序列化器的模型。如何自定義Django REST Framework GET請求的響應?

models.py

class Foo(models.Model): 
    name = models.CharField(max_length=20) 
    description = models.TextField() 
    is_public = models.BooleanField(default=False) 

serializers.py

class FooSerializer(serializers.ModelSerializer): 
    class Meta: 
     model = Foo 

views.py

class FooRetrieveAPIView(RetrieveAPIView): 
    queryset = Foo.objects.all() 
    serializer_class = FooSerializer 

現在噸的結果他的端點正在被前端代碼使用,這就是下一頁顯示的基礎。無論如何,我需要更改狀態200(現有記錄)和404(不存在的記錄)返回結果的結構。

實際結果(香草DRF):

$ curl localhost:8000/foo/1/ # existing record 
{"id": 1, "name": "foo", "description": "foo description", is_public=false} 

$ curl localhost:8000/foo/2/ # non-existent record 
{"detail": "Not found."} 

如何我想要的結果是:

$ curl localhost:8000/foo/1/ 
{"error": "", "foo": {"id": 1, "name": "foo", "description": "foo description", is_public=false}} 

$ curl localhost:8000/foo/2/ 
{"error": "Some custom error message", "foo": null} 

我大部分用香草DRF這樣的事情是很簡單所以這種自定義的響應結構對我來說有點新鮮。

使用Django的版本:1.9.9

使用DRF版本:3.3.x

+0

http://stackoverflow.com/questions/35019030/how-to-return-custom-json-in-django-rest-framework – JClarke

回答

1

可以重寫retrieve方法,在你看來,以更新您的串行響應數據

class FooRetrieveAPIView(RetrieveAPIView): 
    queryset = Foo.objects.all() 
    serializer_class = FooSerializer 

    def retrieve(self, request, *args, **kwargs): 
     instance = self.get_object() 
     serializer = self.get_serializer(instance) 
     data = serializer.data 
     # here you can manipulate your data response 
     return Response(data) 
+0

由於可能的重複。這對'200'響應有效。我需要做一些異常處理來獲得正確的404響應。 – baktin

0

我有一個類似的問題,並不想創建一個自定義異常處理程序,因爲我想要更多的控制定義api調用的錯誤消息秒。 經過一番手忙腳亂之後,我在viewset中使用以下代碼來在使用partial_update更新記錄時獲取自定義錯誤消息。

def partial_update(self, request, *args, **kwargs): 
    partial = kwargs.pop('partial', False) 
    try: 
     instance = self.get_object() 
     serializer = self.get_serializer(instance, data=request.data, partial=partial) 
     serializer.is_valid(raise_exception=True) 
     self.perform_update(serializer) 
     headers = self.get_success_headers(serializer.data) 
     response = {"status": "True", "message": "", "data": serializer.data} 
     return Response(response, status=status.HTTP_201_CREATED, headers=headers) 
    except exception.Http404: 
     headers = "" 
     response = {"status": "False", "message": "Details not found", "data": ""} 
     return Response(response, status=status.HTTP_200_OK, headers=headers) 
相關問題