Implementing Pagination and Filtering

Tutorial 4 of 5

1. Introduction

In this tutorial, we are going to learn how to implement pagination and filtering in Django REST Framework. Pagination is a way to limit the amount of data that's sent in a response, making it easier to manage large amounts of data. Filtering is the process of narrowing down a dataset based on specific criteria.

You will learn:
- How to implement basic pagination.
- How to customize pagination.
- How to filter data in your viewsets.

Prerequisites:
- Basic knowledge of Python.
- Basic understanding of Django and Django REST Framework.
- A working Django project to follow along.

2. Step-by-Step Guide

Pagination

Basic Pagination

By default, Django REST Framework provides pagination. You can enable it in your settings.py file:

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 10
}

This sets a default page size of 10, meaning each page of data returned will contain at most 10 items.

Customizing Pagination

You can also create a custom pagination style. For instance, you could create a pagination class that uses limit and offset:

from rest_framework.pagination import LimitOffsetPagination

class CustomLimitOffsetPagination(LimitOffsetPagination):
    default_limit = 2
    max_limit = 5

Filtering

Filtering allows the client to narrow down the queryset returned by the server based on given parameters. Django REST Framework provides a number of filtering options. The simplest way to filter is by including the filter fields in the queryset definition:

from rest_framework import generics

class UserList(generics.ListAPIView):
    queryset = User.objects.filter(is_staff=True)
    serializer_class = UserSerializer

3. Code Examples

Pagination

Suppose we have a model named Book. We want to paginate the data returned when we list all books.

from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response

class BookPagination(PageNumberPagination):
    page_size = 2
    page_size_query_param = 'page_size'
    max_page_size = 10

    def get_paginated_response(self, data):
        return Response({
            'links': {
                'next': self.get_next_link(),
                'previous': self.get_previous_link()
            },
            'count': self.page.paginator.count,
            'results': data
        })

In the above code, page_size is the number of items per page. page_size_query_param allows the client to change the number of items per page. max_page_size is the maximum number of items per page.

Filtering

Suppose we want to filter the books by their publication date. We can use Django's filtering system:

from rest_framework import filters

class BookList(generics.ListAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer
    filter_backends = [filters.SearchFilter]
    search_fields = ['^publication_date']

In the above code, the caret (^) in search_fields signifies that we want to match the start of the publication date.

4. Summary

In this tutorial, you have learned how to implement and customize pagination, and how to filter data in Django REST Framework. You can now limit the amount of data returned in a response and filter data based on specific criteria.

Next steps for learning could include looking at more complex filtering options, or learning about other features of Django REST Framework.

5. Practice Exercises

  1. Implement pagination on another model in your Django project.

  2. Customize the pagination style to use a limit and offset.

  3. Add filtering to your viewset to allow filtering by a different field.

Once you've completed these exercises, try experimenting with different pagination styles and filters. Remember, the best way to learn is by doing!