Pagination in Django REST Framework (DRF)
Pagination is a technique used to split large datasets into smaller, manageable parts (pages). DRF provides several built-in pagination styles, making it easier to handle large sets of data.
1. PageNumberPagination (Simplest & Most Common)
This is the easiest form of pagination, where items are divided based on page numbers.
How It Works:
- URL pattern: /books/?page=2
- Useful for simple websites where users browse pages using page numbers.
Settings Configuration (Globally Applied)
# bookstore/settings.py
REST_FRAMEWORK = {
‘DEFAULT_PAGINATION_CLASS’: ‘rest_framework.pagination.PageNumberPagination’,
‘PAGE_SIZE’: 5, # Number of items per page
}
Testing
- Accessing /books/ will display the first 5 books.
- Accessing /books/?page=2 will display the next set of books.
2. LimitOffsetPagination (Flexible for Large Datasets)
Pagination using limit and offset query parameters. Ideal for large datasets and data grids.
How It Works:
- URL pattern: /books/?limit=5&offset=10
- limit specifies the number of items to display per page.
- offset specifies the starting point of the items to displa
Settings Configuration (Globally Applied)
# bookstore/settings.py
REST_FRAMEWORK = {
‘DEFAULT_PAGINATION_CLASS’: ‘rest_framework.pagination.LimitOffsetPagination’,
‘PAGE_SIZE’: 5, # Default limit if none is provided
}
Testing
- /books/?limit=5&offset=10 fetches 5 books starting from the 11th item.
- Useful for applications with complex filtering or sorting systems.
3. CursorPagination (Best for Large, Evolving Datasets)
Pagination using cursors for better performance and reliability in large, dynamically changing datasets.
How It Works:
- URL pattern: /books/?cursor=<some_cursor_string>
- Uses an encoded cursor string instead of limit and offset.
- Ensures stable pagination even if new items are added to the database.
Adding a created field to your model
# books/models.py
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=255)
author = models.CharField(max_length=255)
published_date = models.DateField()
price = models.DecimalField(max_digits=10, decimal_places=2)
created = models.DateTimeField(auto_now_add=True) # NEW FIELD
def __str__(self):
return self.title
Now, apply the migration:
python manage.py makemigrations
python manage.py migrate
You should see an output like:
Running migrations:
Applying books.0002_book_created… OK
Settings Configuration (Globally Applied)
# bookstore/settings.py
REST_FRAMEWORK = {
‘DEFAULT_PAGINATION_CLASS’: ‘rest_framework.pagination.CursorPagination’,
‘PAGE_SIZE’: 5,
‘ordering’: Created, # Must be a unique field for stable pagination
}
Testing
- Initial request: /books/ returns the first 5 books sorted by published_date.
- Cursor-based request: /books/?cursor=<some_cursor_string> fetches the next set of books.
Summary
- PageNumberPagination: Simple, page-based navigation. (/books/?page=2)
- LimitOffsetPagination: Flexible, using limit and offset. (/books/?limit=5&offset=10)
- CursorPagination: Efficient for large datasets with dynamic updates. (/books/?cursor=<cursor_string>)
Exercise:
- Add PageNumberPagination in settings.
- Create 15 students in the database.
- Visit /students/?page=2 and see if it loads next 5 students.