Pagination helps split large lists of data into smaller parts. This makes pages load faster and easier to read.
Pagination (PageNumber, Cursor, Limit/Offset) in Django
from rest_framework.pagination import PageNumberPagination, CursorPagination, LimitOffsetPagination # PageNumberPagination example class MyPageNumberPagination(PageNumberPagination): page_size = 10 # CursorPagination example class MyCursorPagination(CursorPagination): page_size = 10 ordering = '-created' # LimitOffsetPagination example class MyLimitOffsetPagination(LimitOffsetPagination): default_limit = 10 max_limit = 50
PageNumberPagination uses page numbers like ?page=2.
CursorPagination uses a cursor string to keep track of position, good for changing data.
class MyPageNumberPagination(PageNumberPagination): page_size = 5
class MyCursorPagination(CursorPagination): page_size = 5 ordering = 'id'
class MyLimitOffsetPagination(LimitOffsetPagination): default_limit = 5 max_limit = 20
This example shows a simple API view that paginates a list of fruit names using page number pagination with 3 items per page.
When you request the API with ?page=1, it returns the first 3 fruits. With ?page=2, it returns the next 3, and so on.
from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.pagination import PageNumberPagination from rest_framework import status class ItemListView(APIView): class MyPagination(PageNumberPagination): page_size = 3 pagination_class = MyPagination() def get(self, request): items = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig', 'grape'] paginator = self.pagination_class page = paginator.paginate_queryset(items, request) return paginator.get_paginated_response(page)
PageNumberPagination is simple and good for static data.
CursorPagination is better for data that changes often because it avoids duplicates or missing items.
LimitOffsetPagination lets clients control how many items to get and where to start.
Pagination splits big data into smaller pages for easier loading and viewing.
Django REST Framework offers PageNumber, Cursor, and LimitOffset pagination styles.
Choose the pagination type based on your data and user needs.