使用django rest框架在元数据中添加字段

时间:2018-04-10 05:31:20

标签: django django-rest-framework

我的应用程序的响应如下,但我想在元数据中添加previous旁边的其他字段,如何将IP添加到元数据

{
 "count": 100,
 "next": "http://127.0.0.1:8000/users/?page=2",
 "previous": null,
 "results": [
         {
          "first_name": "john",
          "last_name": "a",
          "mail": "johnabi@mail.com"
         }
  ]
}

我希望我的结果是:

    {
     "count": 100,
     "next": "http://127.0.0.1:8000/users/?page=2",
     "previous": null,
     "ip-adress":0.0.0(something)
     "results": [
             {
}

1 个答案:

答案 0 :(得分:1)

通过文档custom-pagination-styles,您可以尝试

class CustomPagination(pagination.PageNumberPagination):
    def ip_data(self):
        # YOU CUSTOM CODE HERE
        return '0.0.0.0'

    def get_paginated_response(self, data):

        return Response({
            'next': self.get_next_link(),
            'previous': self.get_previous_link()
            'count': self.page.paginator.count,
            'results': data,
            'ip-adress': self.ip_data()
            # ^^^^^^^^^^^^^^^^^^^^^^
        })

并在设置中更新paginator的数据

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'my_project.core.pagination.CustomPagination',
     #                      ^^^ CHANGE PATH TO YOUR PAGINATOR CLASS ^^^
    'PAGE_SIZE': 100
}