REST framework includes a `PaginationSerializer` class that makes it easy to return paginated data in a way that can then be rendered to arbitrary media types.
REST framework includes support for customizable pagination styles. This allows you to modify how large result sets are split into individual pages of data.
## Paginating basic data
The pagination API can support either:
Let's start by taking a look at an example from the Django documentation.
* Pagination links that are provided as part of the content of the response.
* Pagination links that are included in response headers, such as `Content-Range` or `Link`.
from django.core.paginator import Paginator
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.
objects = ['john', 'paul', 'george', 'ringo']
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.ListMixin` and `generics.GenericAPIView` classes for an example.
paginator = Paginator(objects, 2)
page = paginator.page(1)
page.object_list
# ['john', 'paul']
At this point we've got a page object. If we wanted to return this page object as a JSON response, we'd need to provide the client with context such as next and previous links, so that it would be able to page through the remaining results.
## Setting the pagination style
from rest_framework.pagination import PaginationSerializer
The default pagination style may be set globally, using the `DEFAULT_PAGINATION_CLASS` settings key. For example, to use the built-in limit/offset pagination, you would do:
The `context` argument of the `PaginationSerializer` class may optionally include the request. If the request is included in the context then the next and previous links returned by the serializer will use absolute URLs instead of relative URLs.
We could now return that data in a `Response` object, and it would be rendered into the correct media type.
## Paginating QuerySets
Our first example worked because we were using primitive objects. If we wanted to paginate a queryset or other complex data, we'd need to specify a serializer to use to serialize the result set itself.
We can do this using the `object_serializer_class` attribute on the inner `Meta` class of the pagination serializer. For example.
class UserSerializer(serializers.ModelSerializer):
"""
Serializes user querysets.
"""
class Meta:
model = User
fields = ('username', 'email')
class PaginatedUserSerializer(pagination.PaginationSerializer):
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.
"""
Serializes page objects of user querysets.
"""
class Meta:
object_serializer_class = UserSerializer
We could now use our pagination serializer in a view like this.
## Modifying the pagination style
@api_view('GET')
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.
def user_list(request):
queryset = User.objects.all()
paginator = Paginator(queryset, 20)
page = request.QUERY_PARAMS.get('page')
class LargeResultsSetPagination(PageNumberPagination):
try:
paginate_by = 1000
users = paginator.page(page)
paginate_by_param = 'page_size'
except PageNotAnInteger:
max_paginate_by = 10000
# If page is not an integer, deliver first page.
users = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999),
# deliver last page of results.
users = paginator.page(paginator.num_pages)
serializer_context = {'request': request}
class StandardResultsSetPagination(PageNumberPagination):
serializer = PaginatedUserSerializer(users,
paginate_by = 100
context=serializer_context)
paginate_by_param = 'page_size'
return Response(serializer.data)
max_paginate_by = 1000
## Pagination in the generic views
You can then apply your new style to a view using the `.pagination_class` attribute:
The generic class based views `ListAPIView` and `ListCreateAPIView` provide pagination of the returned querysets by default. You can customise this behaviour by altering the pagination style, by modifying the default number of results, by allowing clients to override the page size using a query parameter, or by turning pagination off completely.
class BillingRecordsView(generics.ListAPIView):
queryset = Billing.objects.all()
serializer = BillingRecordsSerializer
pagination_class = LargeResultsSetPagination
The default pagination style may be set globally, using the `DEFAULT_PAGINATION_SERIALIZER_CLASS`, `PAGINATE_BY`, `PAGINATE_BY_PARAM`, and `MAX_PAGINATE_BY` settings. For example.
Or apply the style globally, using the `DEFAULT_PAGINATION_CLASS` settings key. For example:
'PAGINATE_BY_PARAM': 'page_size', # Allow client to override, using `?page_size=xxx`.
'MAX_PAGINATE_BY': 100 # Maximum limit allowed when using `?page_size=xxx`.
}
You can also set the pagination style on a per-view basis, using the `ListAPIView` generic class-based view.
class PaginatedListView(ListAPIView):
# API Reference
queryset = ExampleModel.objects.all()
serializer_class = ExampleModelSerializer
paginate_by = 10
paginate_by_param = 'page_size'
max_paginate_by = 100
Note that using a `paginate_by` value of `None` will turn off pagination for the view.
## PageNumberPagination
Note if you use the `PAGINATE_BY_PARAM` settings, you also have to set the `paginate_by_param` attribute in your view to `None` in order to turn off pagination for those requests that contain the `paginate_by_param` parameter.
For more complex requirements such as serialization that differs depending on the requested media type you can override the `.get_paginate_by()` and `.get_pagination_serializer_class()` methods.
## LimitOffsetPagination
---
---
# Custom pagination serializers
# Custom pagination styles
To create a custom pagination serializer class you should subclass `pagination.BasePagination` and override the `paginate_queryset(self, queryset, request, view)` and `get_paginated_response(self, data)` methods:
To create a custom pagination serializer class you should override `pagination.BasePaginationSerializer` and set the fields that you want the serializer to return.
* The `paginate_queryset` method is passed the initial queryset and should return an iterable object that contains only the data in the requested page.
* The `get_paginated_response` method is passed the serialized page data and should return a `Response` instance.
You can also override the name used for the object list field, by setting the `results_field` attribute, which defaults to `'results'`.
Note that the `paginate_queryset` method may set state on the pagination instance, that may later be used by the `get_paginated_response` method.
## Example
## Example
For example, to nest a pair of links labelled 'prev' and 'next', and set the name for the results field to 'objects', you might use something like this.
Let's modify the built-in `PageNumberPagination` style, so that instead of include the pagination links in the body of the response, we'll instead include a `Link` header, in a [similar style to the GitHub API][github-link-pagination].
Alternatively, to set your custom pagination serializer on a per-view basis, use the `pagination_serializer_class` attribute on a generic class based view:
The following third party packages are also available.
The following third party packages are also available.
...
@@ -157,5 +110,6 @@ The following third party packages are also available.
...
@@ -157,5 +110,6 @@ The following third party packages are also available.
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.
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.