2015-10-06 54 views
3

所以我有一個分頁的結果列表。這裏的DRF如何通過默認格式是:如何將所有元數據包裝到「元」屬性中?

{ 
    "count": 1023 
    "next": "https://api.example.org/accounts/?page=5", 
    "previous": "https://api.example.org/accounts/?page=3", 
    "results": [ 
     … 
    ] 
} 

如何包裝所有元數據到「元」屬性,以使響應如下所示:

{ 
    "meta": { 
     "count": 1023 
     "next": "https://api.example.org/accounts/?page=5", 
     "previous": "https://api.example.org/accounts/?page=3", 
    }, 
    "results": [ 
     … 
    ] 
} 

編輯:謝謝阿拉斯戴爾爲你的答案。以下是我如何做到的:

from rest_framework import pagination 
from rest_framework.response import Response 

class CustomPagination(pagination.LimitOffsetPagination): 

    def get_paginated_response(self, data): 
    return Response({ 
     'meta': { 
     'next': self.get_next_link(), 
     'previous': self.get_previous_link(), 
     'count': self.count 
     }, 
     'results': data 
    }) 
+2

您可以創建自定義分頁程序並覆蓋'get_paginated_response'方法。 [這個答案](http://stackoverflow.com/questions/31740039/django-rest-framework-pagination-extremely-slow-count/31741778#31741778)應該讓你開始,如果你卡住了,請更新你的問題。 – Alasdair

+0

您應該將解決方案作爲答案發布,而不是編輯您的帖子。 – GwynBleidD

回答

2

您需要implement a custom pagination style將所有元數據包裝到元屬性中。

第1步實現自定義分頁類:

首先,我們將實現一個自定義分頁類WrappedMetadataPagination將從pagination.LimitOffsetPagination繼承。在這種情況下,我們將覆蓋get_paginated_response()並指定我們的自定義分頁輸出樣式。

class WrappedMetadataPagination(pagination.LimitOffsetPagination): 
    """ 
    This custom pagination class wraps the metadata about the results 
    like 'next', 'previous' and 'next' keys into a dictionary with key as 'meta'. 
    """ 

    def get_paginated_response(self, data): 
     return Response({ 
      'meta': { # wrap other keys as dictionary into 'meta' key 
       'next': self.get_next_link(), 
       'previous': self.get_previous_link(), 
       'count': self.count 
      }, 
      'results': data 
     }) 

步驟2安裝在DRF設置自定義類:

實現自定義類之後,您需要在您的DRF設置來指定這個自定義分頁類。

REST_FRAMEWORK = { 
    'DEFAULT_PAGINATION_CLASS': 'my_project.my_app.pagination.WrappedMetadataPagination', # specify the custom pagination class 
...  
} 
相關問題