Django Rest Framework分页:返回包含所请求数据的页面的更简洁方法

时间:2019-05-23 14:55:13

标签: django pagination django-rest-framework

我有一个CustomPagination类,可以搜索给定的帖子数据并返回包含该数据的页面。这确实有效。但是,在处理大量数据时,这可能会导致性能问题。我需要实现一种更干净的方法来搜索帖子数据,而无需遍历页面,并且避免使用number = 1之类的常量

pagination.py

class CustomPagination(PageNumberPagination):

   def paginate_queryset(self, queryset, request, view=None):
      page_size = self.get_page_size(request)
      if not page_size:
         return None

      paginator = self.django_paginator_class(queryset, page_size)
      page_number = request.query_params.get(self.page_query_param, 1)

      if page_number in self.last_page_strings:
         page_number = paginator.num_pages

      id = request.query_params.get('id', None)

      if id:
         post = Post.objects.get(pk=id)
         number = 1
         while number <= paginator.num_pages:
            self.page = paginator.page(number)
            if post in list(self.page):
               break
            number += 1
      else:
         self.page = paginator.page(page_number)


      if paginator.num_pages > 1 and self.template is not None:
         self.display_page_controls = True

      self.request = request

      return list(self.page)

   def get_paginated_response(self, data):
      return Response({
      'next': self.get_next_link(),
      'previous': self.get_previous_link(),
      'count': self.page.paginator.count,
      'total_pages': self.page.paginator.num_pages,
      'results': data
   })

0 个答案:

没有答案