【问题标题】:How to solve error 'RelatedManager' object is not subscriptable?如何解决错误“RelatedManager”对象不可下标?
【发布时间】:2021-03-04 03:53:25
【问题描述】:

我有以下看法

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)

我的自定义分页:


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

得到以下错误:

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

如果我删除 pagination_class 一切正常。无法弄清楚为什么代码不能使用分页。因为cmets依赖post?

【问题讨论】:

    标签: django api django-rest-framework pagination


    【解决方案1】:

    post.comment_set不是一个QuerySet,它是一个QuerySet的经理,你需要调用.all() method [Django-doc]来访问带有所有Comments的查询集:

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

    【讨论】:

    • 非常感谢!
    猜你喜欢
    • 2020-02-17
    • 1970-01-01
    • 2018-02-18
    • 1970-01-01
    • 1970-01-01
    • 2021-04-19
    • 1970-01-01
    • 2011-09-12
    • 1970-01-01
    相关资源
    最近更新 更多