44from collections import OrderedDict
55from rest_framework import serializers
66from rest_framework .views import Response
7- from rest_framework .pagination import PageNumberPagination
7+ from rest_framework .pagination import PageNumberPagination , LimitOffsetPagination
88from 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