Debian Codegraph @

docs/api-guide/pagination.md

raw
1 ---
2 source:
3 - pagination.py
4 ---
5
6 # Pagination
7
8 > Django provides a few classes that help you manage paginated data – that is, data that’s split across several pages, with “Previous/Next” links.
9 >
10 > — [Django documentation][cite]
11
12 REST framework includes support for customizable pagination styles. This allows you to modify how large result sets are split into individual pages of data.
13
14 The pagination API can support either:
15
16 * Pagination links that are provided as part of the content of the response.
17 * Pagination links that are included in response headers, such as `Content-Range` or `Link`.
18
19 The built-in styles currently all use links included as part of the content of the response. This style is more accessible when using the browsable API.
20
21 Pagination is only performed automatically if you're using the generic views or viewsets. If you're using a regular `APIView`, you'll need to call into the pagination API yourself to ensure you return a paginated response. See the source code for the `mixins.ListModelMixin` and `generics.GenericAPIView` classes for an example.
22
23 Pagination can be turned off by setting the pagination class to `None`.
24
25 ## Setting the pagination style
26
27 The pagination style may be set globally, using the `DEFAULT_PAGINATION_CLASS` and `PAGE_SIZE` setting keys. For example, to use the built-in limit/offset pagination, you would do something like this:
28
29 REST_FRAMEWORK = {
30 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
31 'PAGE_SIZE': 100
32 }
33
34 Note that you need to set both the pagination class, and the page size that should be used. Both `DEFAULT_PAGINATION_CLASS` and `PAGE_SIZE` are `None` by default.
35
36 You can also set the pagination class on an individual view by using the `pagination_class` attribute. Typically you'll want to use the same pagination style throughout your API, although you might want to vary individual aspects of the pagination, such as default or maximum page size, on a per-view basis.
37
38 ## Modifying the pagination style
39
40 If you want to modify particular aspects of the pagination style, you'll want to override one of the pagination classes, and set the attributes that you want to change.
41
42 class LargeResultsSetPagination(PageNumberPagination):
43 page_size = 1000
44 page_size_query_param = 'page_size'
45 max_page_size = 10000
46
47 class StandardResultsSetPagination(PageNumberPagination):
48 page_size = 100
49 page_size_query_param = 'page_size'
50 max_page_size = 1000
51
52 You can then apply your new style to a view using the `pagination_class` attribute:
53
54 class BillingRecordsView(generics.ListAPIView):
55 queryset = Billing.objects.all()
56 serializer_class = BillingRecordsSerializer
57 pagination_class = LargeResultsSetPagination
58
59 Or apply the style globally, using the `DEFAULT_PAGINATION_CLASS` settings key. For example:
60
61 REST_FRAMEWORK = {
62 'DEFAULT_PAGINATION_CLASS': 'apps.core.pagination.StandardResultsSetPagination'
63 }
64
65 ## Details and limitations
66
67 Proper use of pagination requires a little attention to detail. You'll need to think about what ordering you want the scheme to be applied against.
68
69 You can modify the ordering in multiple ways:
70
71 * Using the `OrderingFilter` filter class together with the pagination class in the view definition.
72 * Setting the `ordering` attribute on the `Meta` class of the model whose records are being paginated.
73 * Explicitly calling `order_by` on the view's `queryset`.
74 * If using the [`CursorPagination`](#cursorpagination) class, overriding the `ordering` attribute
75
76 When using `OrderingFilter`, you should strongly consider restricting the fields that the user may order by.
77
78 For `CursorPagination`, the default is to order by `"-created"`. This assumes that **there must be a 'created' timestamp field** on the model instances, and will present a "timeline" style paginated view, with the most recently added items first.
79
80 Proper usage of pagination should have an ordering field that satisfies the following:
81
82 * Should be an unchanging value, such as a timestamp, slug, or other field that is only set once, on creation.
83 * Should be unique, or nearly unique if using `CursorPagination`. The `CursorPagination` implementation uses a smart "position plus offset" style that allows it to properly support not-strictly-unique values as the ordering. Millisecond precision timestamps are a good example.
84 * Should be a non-nullable value that can be coerced to a string.
85 * Should not be a float. Precision errors easily lead to incorrect results. Hint: use decimals instead. (If you already have a float field and must paginate on that, an [example `CursorPagination` subclass that uses decimals to limit precision is available here][float_cursor_pagination_example].)
86 * The field should have a database index.
87
88 Using an ordering field that does not satisfy these constraints will generally still work, but the results might be suboptimal or outright inconsistent depending on the chosen scheme. These inconsistencies might manifest as either missing records or duplicate records:
89
90 class Product(models.Model):
91 name = models.CharField(max_length=100)
92 category = models.CharField(max_length=100)
93 # No unique/indexed field used for ordering
94
95 class ProductSerializer(serializers.ModelSerializer):
96 class Meta:
97 model = Product
98 fields = '__all__'
99
100 # 1. Inconsistent LimitOffsetPagination
101 class UnreliableProductViewSet(viewsets.ModelViewSet):
102 # Many duplicates, inconsistent pages
103 queryset = Product.objects.all().order_by('category')
104 serializer_class = ProductSerializer
105 pagination_class = pagination.LimitOffsetPagination
106
107 # 2. Inconsistent CursorPagination (Will fail or be buggy)
108 class RiskyCursorPagination(pagination.CursorPagination):
109 page_size = 10
110 # Problematic: 'name' is not unique and can change
111 ordering = 'name'
112
113 By ensuring the final ordering field is unique and indexed (like id or a created timestamp), we guarantee that the cursor position remains stable:
114
115 class SecureProduct(models.Model):
116 name = models.CharField(max_length=100)
117 created_at = models.DateTimeField(auto_now_add=True, db_index=True)
118
119 class SecureProductSerializer(serializers.ModelSerializer):
120 class Meta:
121 model = SecureProduct
122 fields = '__all__'
123
124 # 1. Consistent PageNumberPagination with Multiple Ordering
125 class ReliableProductViewSet(viewsets.ModelViewSet):
126 # Combining a non-unique field with a unique ID ensures consistency
127 queryset = SecureProduct.objects.all().order_by('name', 'id')
128 serializer_class = SecureProductSerializer
129 pagination_class = pagination.PageNumberPagination
130
131 # 2. Recommended CursorPagination Usage
132 class StandardCursorPagination(pagination.CursorPagination):
133 page_size = 10
134 # Unique-ish, indexed, and unchanging
135 ordering = '-created_at'
136
137 class AccurateProductViewSet(viewsets.ModelViewSet):
138 queryset = SecureProduct.objects.all()
139 serializer_class = SecureProductSerializer
140 pagination_class = StandardCursorPagination
141
142 ---
143
144 ## API Reference
145
146 ### PageNumberPagination
147
148 This pagination style accepts a single number page number in the request query parameters.
149
150 **Request**:
151
152 GET https://api.example.org/accounts/?page=4
153
154 **Response**:
155
156 HTTP 200 OK
157 {
158 "count": 1023,
159 "next": "https://api.example.org/accounts/?page=5",
160 "previous": "https://api.example.org/accounts/?page=3",
161 "results": [
162 …
163 ]
164 }
165
166 #### Setup
167
168 To enable the `PageNumberPagination` style globally, use the following configuration, and set the `PAGE_SIZE` as desired:
169
170 REST_FRAMEWORK = {
171 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
172 'PAGE_SIZE': 100
173 }
174
175 On `GenericAPIView` subclasses you may also set the `pagination_class` attribute to select `PageNumberPagination` on a per-view basis.
176
177 By default, the query parameter name used for pagination is `page`.
178 This can be customized by subclassing `PageNumberPagination` and overriding the `page_query_param` attribute.
179
180 For example:
181
182 from rest_framework.pagination import PageNumberPagination
183
184 class CustomPagination(PageNumberPagination):
185 page_query_param = 'p'
186
187 With this configuration, clients would request pages using `?p=2` instead of `?page=2`.
188
189 #### Configuration
190
191 The `PageNumberPagination` class includes a number of attributes that may be overridden to modify the pagination style.
192
193 To set these attributes you should override the `PageNumberPagination` class, and then enable your custom pagination class as above.
194
195 * `django_paginator_class` - The Django Paginator class to use. Default is `django.core.paginator.Paginator`, which should be fine for most use cases.
196 * `page_size` - A numeric value indicating the page size. If set, this overrides the `PAGE_SIZE` setting. Defaults to the same value as the `PAGE_SIZE` settings key.
197 * `page_query_param` - A string value indicating the name of the query parameter to use for the pagination control.
198 * `page_size_query_param` - If set, this is a string value indicating the name of a query parameter that allows the client to set the page size on a per-request basis. Defaults to `None`, indicating that the client may not control the requested page size.
199 * `max_page_size` - If set, this is a numeric value indicating the maximum allowable requested page size. This attribute is only valid if `page_size_query_param` is also set.
200 * `last_page_strings` - A list or tuple of string values indicating values that may be used with the `page_query_param` to request the final page in the set. Defaults to `('last',)`. For example, use `?page=last` to go directly to the last page.
201 * `template` - The name of a template to use when rendering pagination controls in the browsable API. May be overridden to modify the rendering style, or set to `None` to disable HTML pagination controls completely. Defaults to `"rest_framework/pagination/numbers.html"`.
202
203 ---
204
205 ### LimitOffsetPagination
206
207 This pagination style mirrors the syntax used when looking up multiple database records. The client includes both a "limit" and an
208 "offset" query parameter. The limit indicates the maximum number of items to return, and is equivalent to the `page_size` in other styles. The offset indicates the starting position of the query in relation to the complete set of unpaginated items.
209
210 **Request**:
211
212 GET https://api.example.org/accounts/?limit=100&offset=400
213
214 **Response**:
215
216 HTTP 200 OK
217 {
218 "count": 1023,
219 "next": "https://api.example.org/accounts/?limit=100&offset=500",
220 "previous": "https://api.example.org/accounts/?limit=100&offset=300",
221 "results": [
222 …
223 ]
224 }
225
226 #### Setup
227
228 To enable the `LimitOffsetPagination` style globally, use the following configuration:
229
230 REST_FRAMEWORK = {
231 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination'
232 }
233
234 Optionally, you may also set a `PAGE_SIZE` key. If the `PAGE_SIZE` parameter is also used then the `limit` query parameter will be optional, and may be omitted by the client.
235
236 On `GenericAPIView` subclasses you may also set the `pagination_class` attribute to select `LimitOffsetPagination` on a per-view basis.
237
238 #### Configuration
239
240 The `LimitOffsetPagination` class includes a number of attributes that may be overridden to modify the pagination style.
241
242 To set these attributes you should override the `LimitOffsetPagination` class, and then enable your custom pagination class as above.
243
244 * `default_limit` - A numeric value indicating the limit to use if one is not provided by the client in a query parameter. Defaults to the same value as the `PAGE_SIZE` settings key.
245 * `limit_query_param` - A string value indicating the name of the "limit" query parameter. Defaults to `'limit'`.
246 * `offset_query_param` - A string value indicating the name of the "offset" query parameter. Defaults to `'offset'`.
247 * `max_limit` - If set this is a numeric value indicating the maximum allowable limit that may be requested by the client. Defaults to `None`.
248 * `template` - The name of a template to use when rendering pagination controls in the browsable API. May be overridden to modify the rendering style, or set to `None` to disable HTML pagination controls completely. Defaults to `"rest_framework/pagination/numbers.html"`.
249
250 ---
251
252 ### CursorPagination
253
254 The cursor-based pagination presents an opaque "cursor" indicator that the client may use to page through the result set. This pagination style only presents forward and reverse controls, and does not allow the client to navigate to arbitrary positions.
255
256 Cursor based pagination requires that there is a unique, unchanging ordering of items in the result set. This ordering might typically be a creation timestamp on the records, as this presents a consistent ordering to paginate against.
257
258 Cursor based pagination is more complex than other schemes. It also requires that the result set presents a fixed ordering, and does not allow the client to arbitrarily index into the result set. However it does provide the following benefits:
259
260 * Provides a consistent pagination view. When used properly `CursorPagination` ensures that the client will never see the same item twice when paging through records, even when new items are being inserted by other clients during the pagination process.
261 * Supports usage with very large datasets. With extremely large datasets pagination using offset-based pagination styles may become inefficient or unusable. Cursor based pagination schemes instead have fixed-time properties, and do not slow down as the dataset size increases.
262
263 For more technical details on the implementation we use for cursor pagination, the ["Building cursors for the Disqus API"][disqus-cursor-api] blog post gives a good overview of the basic approach.
264
265 #### Setup
266
267 To enable the `CursorPagination` style globally, use the following configuration, modifying the `PAGE_SIZE` as desired:
268
269 REST_FRAMEWORK = {
270 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.CursorPagination',
271 'PAGE_SIZE': 100
272 }
273
274 On `GenericAPIView` subclasses you may also set the `pagination_class` attribute to select `CursorPagination` on a per-view basis.
275
276 #### Configuration
277
278 The `CursorPagination` class includes a number of attributes that may be overridden to modify the pagination style.
279
280 To set these attributes you should override the `CursorPagination` class, and then enable your custom pagination class as above.
281
282 * `page_size` = A numeric value indicating the page size. If set, this overrides the `PAGE_SIZE` setting. Defaults to the same value as the `PAGE_SIZE` settings key.
283 * `cursor_query_param` = A string value indicating the name of the "cursor" query parameter. Defaults to `'cursor'`.
284 * `ordering` = This should be a string, or list of strings, indicating the field against which the cursor based pagination will be applied. For example: `ordering = 'slug'`. Defaults to `-created`. This value may also be overridden by using `OrderingFilter` on the view.
285 * `template` = The name of a template to use when rendering pagination controls in the browsable API. May be overridden to modify the rendering style, or set to `None` to disable HTML pagination controls completely. Defaults to `"rest_framework/pagination/previous_and_next.html"`.
286
287 ---
288
289 ## Custom pagination styles
290
291 To create a custom pagination serializer class, you should inherit the subclass `pagination.BasePagination`, override the `paginate_queryset(self, queryset, request, view=None)`, and `get_paginated_response(self, data)` methods:
292
293 * The `paginate_queryset` method is passed to the initial queryset and should return an iterable object. That object contains only the data in the requested page.
294 * The `get_paginated_response` method is passed to the serialized page data and should return a `Response` instance.
295
296 Note that the `paginate_queryset` method may set state on the pagination instance, that may later be used by the `get_paginated_response` method.
297
298 ### Example
299
300 Suppose we want to replace the default pagination output style with a modified format that includes the next and previous links under in a nested 'links' key. We could specify a custom pagination class like so:
301
302 class CustomPagination(pagination.PageNumberPagination):
303 def get_paginated_response(self, data):
304 return Response({
305 'links': {
306 'next': self.get_next_link(),
307 'previous': self.get_previous_link()
308 },
309 'count': self.page.paginator.count,
310 'results': data
311 })
312
313 We'd then need to set up the custom class in our configuration:
314
315 REST_FRAMEWORK = {
316 'DEFAULT_PAGINATION_CLASS': 'my_project.apps.core.pagination.CustomPagination',
317 'PAGE_SIZE': 100
318 }
319
320 Note that if you care about how the ordering of keys is displayed in responses in the browsable API you might choose to use an `OrderedDict` when constructing the body of paginated responses, but this is optional.
321
322 ### Using your custom pagination class
323
324 To have your custom pagination class be used by default, use the `DEFAULT_PAGINATION_CLASS` setting:
325
326 REST_FRAMEWORK = {
327 'DEFAULT_PAGINATION_CLASS': 'my_project.apps.core.pagination.LinkHeaderPagination',
328 'PAGE_SIZE': 100
329 }
330
331 API responses for list endpoints will now include a `Link` header, instead of including the pagination links as part of the body of the response, for example:
332
333 ![Link Header][link-header]
334
335 *A custom pagination style, using the 'Link' header*
336
337 ---
338
339 ## HTML pagination controls
340
341 By default using the pagination classes will cause HTML pagination controls to be displayed in the browsable API. There are two built-in display styles. The `PageNumberPagination` and `LimitOffsetPagination` classes display a list of page numbers with previous and next controls. The `CursorPagination` class displays a simpler style that only displays a previous and next control.
342
343 ### Customizing the controls
344
345 You can override the templates that render the HTML pagination controls. The two built-in styles are:
346
347 * `rest_framework/pagination/numbers.html`
348 * `rest_framework/pagination/previous_and_next.html`
349
350 Providing a template with either of these paths in a global template directory will override the default rendering for the relevant pagination classes.
351
352 Alternatively you can disable HTML pagination controls completely by subclassing on of the existing classes, setting `template = None` as an attribute on the class. You'll then need to configure your `DEFAULT_PAGINATION_CLASS` settings key to use your custom class as the default pagination style.
353
354 #### Low-level API
355
356 The low-level API for determining if a pagination class should display the controls or not is exposed as a `display_page_controls` attribute on the pagination instance. Custom pagination classes should be set to `True` in the `paginate_queryset` method if they require the HTML pagination controls to be displayed.
357
358 The `.to_html()` and `.get_html_context()` methods may also be overridden in a custom pagination class in order to further customize how the controls are rendered.
359
360 ---
361
362 ## Third party packages
363
364 The following third party packages are also available.
365
366 ### DRF-extensions
367
368 The [`DRF-extensions` package][drf-extensions] includes a [`PaginateByMaxMixin` mixin class][paginate-by-max-mixin] that allows your API clients to specify `?page_size=max` to obtain the maximum allowed page size.
369
370 ### drf-proxy-pagination
371
372 The [`drf-proxy-pagination` package][drf-proxy-pagination] includes a `ProxyPagination` class which allows to choose pagination class with a query parameter.
373
374 ### link-header-pagination
375
376 The [`django-rest-framework-link-header-pagination` package][drf-link-header-pagination] includes a `LinkHeaderPagination` class which provides pagination via an HTTP `Link` header as described in [GitHub REST API documentation][github-traversing-with-pagination].
377
378 [cite]: https://docs.djangoproject.com/en/stable/topics/pagination/
379 [link-header]: ../img/link-header-pagination.png
380 [drf-extensions]: https://chibisov.github.io/drf-extensions/docs/
381 [paginate-by-max-mixin]: https://chibisov.github.io/drf-extensions/docs/#paginatebymaxmixin
382 [drf-proxy-pagination]: https://github.com/tuffnatty/drf-proxy-pagination
383 [drf-link-header-pagination]: https://github.com/tbeadle/django-rest-framework-link-header-pagination
384 [disqus-cursor-api]: https://cra.mr/2011/03/08/building-cursors-for-the-disqus-api
385 [float_cursor_pagination_example]: https://gist.github.com/keturn/8bc88525a183fd41c73ffb729b8865be#file-fpcursorpagination-py
386 [github-traversing-with-pagination]: https://docs.github.com/en/rest/guides/traversing-with-pagination