2014-10-30 46 views
0

可以說,我有一個模型:在Django rest框架中,如何更改json響應的形式?

class MyModel(models.Model): 
    name = models.CharField(max_length=100) 
    description= models.TextField() 
    ... 

然後創建ModelViewSet與HyperLinkedSerializer,所以當我把我的/ API/mymodels endpint我得到的反應是這樣的:

{ 
    "count": 2, 
    "next": null, 
    "previous": null, 
    "results": [ 
     { "name": "somename", "description": "desc"}, 
     { "name": "someothername", "description": "asdasd"}, 
    ] 
} 

,當我打電話/ API/mymodels/1,我得到:

{ "name": "somename", "description": "asdasd"} 

但我想獲得的是:

{ 
    "metadata":{ ...}, 
    "results": { "name": "somename", "description": "desc"} 
} 

我想在我的網站上爲所有模型使用這種格式,所以我不想更改每個視圖集,我想在一個類中實現它(最有可能),然後將其用於所有視圖集。

所以我的問題是:哪個渲染器或序列化程序或其他類(我真的不知道)應該改變或創建以獲得這種行爲的JSON響應?

回答

1

第一個響應似乎是由分頁序列化程序確定的分頁響應。您可以創建將使用自定義格式的a custom pagination serializer。您正在尋找類似如下的內容:

class MetadataSerialier(pagination.BasePaginationSerializer): 
    count = serializers.Field(source='paginator.count') 
    next = NextPageField(source='*') 
    previous = PreviousPageField(source='*') 


class CustomPaginationSerializer(pagination.BasePaginationSerializer): 
    metadata = MetadataSerializer(source='*') 

這應該給你類似以下的輸出:

{ 
    "metadata": { 
     "count": 2, 
     "next": null, 
     "previous": null 
    }, 
    "results": [ 
     { "name": "somename", "description": "desc"}, 
     { "name": "someothername", "description": "asdasd"} 
    ] 
} 

分頁串行器可以通過設置,as described in the documentation全局設置。

REST_FRAMEWORK = { 
    'DEFAULT_PAGINATION_SERIALIZER_CLASS': { 
     'full.path.to.CustomPaginationSerializer', 
    } 
}