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