Pagination in Django
DRF includes pagination classes that can be used to paginate large result sets. Here's an example view that paginates a list of books:
python
Copy code
from rest_framework import generics, pagination
from .models import Book
from .serializers import BookSerializer
class BookList(generics.ListCreateAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializer
pagination_class = pagination.PageNumberPagination
In this example, we specify the PageNumberPagination class as the pagination class. This will paginate the result set using page numbers.
We can customize the pagination settings by creating a custom pagination class:
python
from rest_framework import pagination
class CustomPagination(pagination.PageNumberPagination):
page_size = 10
page_size_query_param = 'page_size'
max_page_size = 100
class BookList(generics.ListCreateAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializer
pagination_class = CustomPagination
In this example, we create a custom pagination class that sets the page size to 10 by default and allows clients to specify a different page size using the page_size query parameter. The max_page_size attribute limits the maximum page size that can be requested.
No comments:
Post a Comment