pagination.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. from collections import OrderedDict
  2. from rest_framework.pagination import LimitOffsetPagination as _LimitOffsetPagination
  3. from rest_framework.response import Response
  4. def get_paginated_response(*, pagination_class, serializer_class, queryset, request, view):
  5. paginator = pagination_class()
  6. page = paginator.paginate_queryset(queryset, request, view=view)
  7. if page is not None:
  8. serializer = serializer_class(page, many=True)
  9. return paginator.get_paginated_response(serializer.data)
  10. serializer = serializer_class(queryset, many=True)
  11. return Response(data=serializer.data)
  12. class LimitOffsetPagination(_LimitOffsetPagination):
  13. default_limit = 10
  14. max_limit = 50
  15. def get_paginated_data(self, data):
  16. return OrderedDict(
  17. [
  18. ("limit", self.limit),
  19. ("offset", self.offset),
  20. ("count", self.count),
  21. ("next", self.get_next_link()),
  22. ("previous", self.get_previous_link()),
  23. ("results", data),
  24. ]
  25. )
  26. def get_paginated_response(self, data):
  27. """
  28. We redefine this method in order to return `limit` and `offset`.
  29. This is used by the frontend to construct the pagination itself.
  30. """
  31. return Response(
  32. OrderedDict(
  33. [
  34. ("limit", self.limit),
  35. ("offset", self.offset),
  36. ("count", self.count),
  37. ("next", self.get_next_link()),
  38. ("previous", self.get_previous_link()),
  39. ("results", data),
  40. ]
  41. )
  42. )