Skip to content

Commit 4465ca8

Browse files
author
Sjoerd Arendsen
committed
Add LimitOffsetPagination
1 parent eaaad66 commit 4465ca8

File tree

1 file changed

+49
-1
lines changed

1 file changed

+49
-1
lines changed

‎rest_framework_json_api/pagination.py

+49-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
from collections import OrderedDict
55
from rest_framework import serializers
66
from rest_framework.views import Response
7-
from rest_framework.pagination import PageNumberPagination
7+
from rest_framework.pagination import PageNumberPagination, LimitOffsetPagination
88
from rest_framework.templatetags.rest_framework import replace_query_param
99

1010

@@ -47,3 +47,51 @@ def get_paginated_response(self, data):
4747
('prev', self.build_link(previous))
4848
])
4949
})
50+
51+
52+
class LimitOffsetPagination(LimitOffsetPagination):
53+
"""
54+
A limit/offset based style. For example:
55+
http://api.example.org/accounts/?page[limit]=100
56+
http://api.example.org/accounts/?page[offset]=400&page[limit]=100
57+
"""
58+
limit_query_param = 'page[limit]'
59+
offset_query_param = 'page[offset]'
60+
61+
def get_last_link(self):
62+
if self.count == 0:
63+
return None
64+
65+
url = self.request.build_absolute_uri()
66+
url = replace_query_param(url, self.limit_query_param, self.limit)
67+
68+
offset = self.count - self.limit
69+
return replace_query_param(url, self.offset_query_param, offset)
70+
71+
def get_first_link(self):
72+
if self.count == 0:
73+
return None
74+
75+
url = self.request.build_absolute_uri()
76+
url = replace_query_param(url, self.limit_query_param, self.limit)
77+
78+
offset = 0
79+
return replace_query_param(url, self.offset_query_param, offset)
80+
81+
def get_paginated_response(self, data):
82+
return Response({
83+
'results': data,
84+
'meta': {
85+
'pagination': OrderedDict([
86+
('count', self.count),
87+
('limit', self.limit),
88+
('offset', self.offset),
89+
])
90+
},
91+
'links': OrderedDict([
92+
('first', self.get_first_link()),
93+
('last', self.get_last_link()),
94+
('next', self.get_next_link()),
95+
('prev', self.get_previous_link())
96+
])
97+
})

0 commit comments

Comments
 (0)