Pagination
REST framework includes support for customizable pagination styles. This allows you to modify how large result sets are split into individual pages of data.
Pagination is only performed automatically if you're using the generic views or viewsets.
Setting the Pagination Style
The pagination style may be set globally using the DEFAULT_PAGINATION_CLASS and PAGE_SIZE setting keys.
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
'PAGE_SIZE': 100
}You can also set the pagination class on an individual view by setting the pagination_class attribute.
from rest_framework import generics
from rest_framework.pagination import PageNumberPagination
from .models import Article
from .serializers import ArticleSerializer
class StandardResultsSetPagination(PageNumberPagination):
page_size = 100
page_size_query_param = 'page_size'
max_page_size = 1000
class ArticleListView(generics.ListAPIView):
queryset = Article.objects.all()
serializer_class = ArticleSerializer
pagination_class = StandardResultsSetPaginationBuilt-in Pagination Styles
PageNumberPagination
This pagination style accepts a single number page number in the request query parameters.
Request:GET https://api.example.org/accounts/?page=4
Response:
{
"count": 1023,
"next": "https://api.example.org/accounts/?page=5",
"previous": "https://api.example.org/accounts/?page=3",
"results": [
// ...
]
}LimitOffsetPagination
This pagination style accepts limit and offset parameters, mimicking SQL syntax.
Request:GET https://api.example.org/accounts/?limit=100&offset=400
Response:
{
"count": 1023,
"next": "https://api.example.org/accounts/?limit=100&offset=500",
"previous": "https://api.example.org/accounts/?limit=100&offset=300",
"results": [
// ...
]
}CursorPagination
Cursor pagination presents an opaque "cursor" indicator that the client may use to page through the result set. It provides forward and reverse controls, but does not allow navigating to arbitrary pages.
Cursor pagination is highly efficient for extremely large datasets compared to offset-based pagination.
Request:GET https://api.example.org/accounts/?cursor=cD0xNSZvPWFjY291bnRfaWQ%3D
Response:
{
"next": "https://api.example.org/accounts/?cursor=cD0xNSZvPWFjY291bnRfaWQ%3D",
"previous": null,
"results": [
// ...
]
}