Last modified: Mar 10, 2025 By Alexander Williams
Pagination in Django Rest Framework: LimitOffset vs PageNumber
Pagination is essential for managing large datasets in APIs. Django Rest Framework (DRF) offers two main pagination styles: LimitOffset and PageNumber. This article compares both methods.
Table Of Contents
What is Pagination?
Pagination divides large datasets into smaller chunks. It improves performance and user experience. DRF provides built-in support for pagination.
PageNumber Pagination
PageNumber pagination divides data into pages. Each page contains a fixed number of items. It is simple and widely used.
To enable PageNumber pagination, add the following to your settings:
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10
}
This sets the default pagination class and page size. The API will return 10 items per page.
Example Request
To request the second page, use the following URL:
GET /api/items/?page=2
Example Response
{
"count": 100,
"next": "http://api.example.com/items/?page=3",
"previous": "http://api.example.com/items/?page=1",
"results": [...]
}
The response includes the total count, next and previous page URLs, and the results.
LimitOffset Pagination
LimitOffset pagination allows clients to specify the limit and offset. It is more flexible than PageNumber pagination.
To enable LimitOffset pagination, add the following to your settings:
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
'PAGE_SIZE': 10
}
This sets the default pagination class and page size. The API will return 10 items per page by default.
Example Request
To request items 11 to 20, use the following URL:
GET /api/items/?limit=10&offset=10
Example Response
{
"count": 100,
"next": "http://api.example.com/items/?limit=10&offset=20",
"previous": "http://api.example.com/items/?limit=10&offset=0",
"results": [...]
}
The response includes the total count, next and previous page URLs, and the results.
PageNumber vs LimitOffset
Both pagination methods have their pros and cons. PageNumber is simpler and more intuitive. LimitOffset offers more flexibility.
PageNumber is better for fixed-size pages. LimitOffset is better for custom queries. Choose the method that best fits your use case.
Conclusion
Pagination is crucial for managing large datasets in APIs. DRF provides two main pagination methods: PageNumber and LimitOffset. Each has its strengths and weaknesses.
For more on DRF, check out our guides on Using Permissions in Django Rest Framework and Django Rest Framework ViewSets and Routers Guide.