How to solve error 'RelatedManager' object is not subscriptable?

Viewed 301

I have the following view

class CommentViewSet(ModelViewSet):
    queryset = Comment.objects.all()
    serializer_class = CommentsSerializer
    permission_classes = [CustomPermissionClass]
    pagination_class = MyLimitOffsetPagination

    def get_queryset(self):
        review = get_object_or_404(Post, pk=self.kwargs.get('post_id'))
        return post.comment_set

    def perform_create(self, serializer):
        review = get_object_or_404(Post, pk=self.kwargs.get('post_id'))
        serializer.save(author=self.request.user, post=post)

My Custom pagination:


class MyLimitOffsetPagination(LimitOffsetPagination):
    default_limit = 1
    max_limit = 10

Getting the following error:

'RelatedManager' object is not subscriptable. Exception location: paginate_queryset

If I delete the pagination_class everything is okay. Can't figure out why the code does not working with pagination. Because of comments depend on posts?

1 Answers

post.comment_set is not a QuerySet, it is the manager of a QuerySet, you need to call .all() method [Django-doc] to access the queryset with all the Comments:

def get_queryset(self):
    review = get_object_or_404(Post, pk=self.kwargs.get('post_id'))
    #             call .all() ↓
    return post.comment_set.all()
Related