Django Rest Framework: How to handle custom pagination with nested serializers?
This might be a silly question, but I'm currently working on a Django Rest Framework (DRF) application where I'm trying to implement custom pagination for a nested serializer. I have a `Book` model that has a many-to-many relationship with an `Author` model. When I paginate the list of books, I want the response to include the paginated books along with their associated authors, but the authors should also be paginated. I created a custom pagination class that looks like this: ```python from rest_framework.pagination import PageNumberPagination class CustomPagination(PageNumberPagination): page_size = 5 page_size_query_param = 'page_size' max_page_size = 100 ``` I then set up my serializer for the `Author` model like this: ```python from rest_framework import serializers class AuthorSerializer(serializers.ModelSerializer): class Meta: model = Author fields = ['id', 'name'] ``` Next, I have the `BookSerializer` which includes the nested authors: ```python class BookSerializer(serializers.ModelSerializer): authors = AuthorSerializer(many=True) class Meta: model = Book fields = ['id', 'title', 'authors'] ``` When I try to fetch the paginated list of books using the DRF view, it does return the books correctly, but the authors are not paginated; I get all authors for each book, leading to excessive data in the response: ```python from rest_framework.views import APIView from rest_framework.response import Response class BookListView(APIView): pagination_class = CustomPagination def get(self, request): books = Book.objects.all() paginator = self.pagination_class() paginated_books = paginator.paginate_queryset(books, request) serializer = BookSerializer(paginated_books, many=True) return paginator.get_paginated_response(serializer.data) ``` Is there a way to adjust the `AuthorSerializer` so that it only includes a paginated subset of authors? I’ve tried using `SerializerMethodField` for custom behavior, but I’m struggling to figure out how to paginate the nested authors without running into performance issues or incorrect data. Any guidance on how to implement this would be greatly appreciated! I'm using Django 3.2 and DRF 3.12. Am I approaching this the right way?