Django Rest Framework: How to paginate a nested serializer without losing parent context
Hey everyone, I'm running into an issue that's driving me crazy... I'm building a feature where I'm working with Django Rest Framework and trying to implement pagination in a nested serializer structure... I have a `Post` model that has a ForeignKey to a `User` model, and each `Post` can have multiple `Comment` instances. I want to paginate the `Comment` data when retrieving a specific `Post`, but I also want to ensure the `User` data is included in the response without losing the parent context. My serializers look like this: ```python from rest_framework import serializers from .models import Post, Comment, User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username'] class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = ['id', 'content'] class PostSerializer(serializers.ModelSerializer): comments = CommentSerializer(many=True) user = UserSerializer() class Meta: model = Post fields = ['id', 'title', 'content', 'user', 'comments'] def to_representation(self, instance): representation = super().to_representation(instance) representation['comments'] = self.paginate_comments(instance) return representation def paginate_comments(self, instance): # Pagination logic here pass ``` I'm struggling with implementing the `paginate_comments` method effectively. I want to use Django's built-in pagination classes but need to seem to figure out how to apply it to the nested comments while still returning the parent `Post` data in the response. I tried using `PageNumberPagination`, but I kept getting an behavior: `AssertionError: The 'queryset' argument must be an instance of 'QuerySet'.` This happens because I'm passing the list of `Comment` instances directly instead of a queryset. Could anyone guide me on how to properly paginate the comments in the context of the parent `Post` serializer? I'm using Django 3.2 and Django Rest Framework 3.12. Any help would be greatly appreciated! I'd be grateful for any help. Thanks in advance!