当前位置:  开发笔记 > 后端 > 正文

在我的ViewSet中使用detail_route时,在DRF序列化程序中接收"请求"的KeyError

如何解决《在我的ViewSet中使用detail_route时,在DRF序列化程序中接收"请求"的KeyError》经验,为你挑选了1个好方法。

这是我的ViewSet:

class PostViewSet(viewsets.ModelViewSet):
    serializer_class = PostSerializer
    permission_classes = (IsAuthenticated, IsOwnerDeleteOrReadOnly)

    def get_queryset(self):
        return Post.objects.filter(location=self.request.user.userextended.location)

    def perform_create(self, serializer):
        serializer.save(owner=self.request.user, location=self.request.user.userextended.location)

    def get_serializer_context(self):
            """
            Extra context provided to the serializer class.
            """
            return {
                'format': self.format_kwarg,
                'view': self,
                'location': self.request.user.userextended.location
            }

    @detail_route(methods=['post'], permission_classes=[IsAuthenticated, IsFromLocation])
    def like(self, request, pk=None):
        post = self.get_object()
        post.usersVoted.add(request.user)
        return Response(status=status.HTTP_204_NO_CONTENT)

    @detail_route(methods=['get'], permission_classes=[IsAuthenticated, ValidPostPkInKwargs, IsFromPostLocation])
    def replies(self, request, pk=None):
        post = self.get_object()
        replies = post.postreply_set.all()
        serializer = PostReplySerializer(replies, many=True)
        return Response(serializer.data)

这是我的PostReplySerializer:

class PostReplySerializer(serializers.ModelSerializer):
    owner = serializers.SlugRelatedField(slug_field='username', read_only=True)
    voted = serializers.SerializerMethodField()

    def get_voted(self, obj):
        return self.context['request'].user in obj.usersVoted.all()

    class Meta:
        model = PostReply
        fields = ('id', 'owner', 'post', 'voted', 'location')

错误指向该行

return self.context['request'].user in obj.usersVoted.all()

并说:

KeyError at /URL/20/replies/
'request'

任何想法为什么DRF说"请求"是一个关键错误,即使(根据我的理解)它应该自动进入self.context

请注意,PostViewSet对于所有其他请求(如果我收到帖子,获取帖子列表等),它的效果非常好.它只是不起作用replies.



1> Kaviraj Kana..:

它不在self.context中,因为您已覆盖get_serializer_contextrequest对象通过此方法附加到上下文。只需添加request: self.request您的return语句即可get_serializer_context解决问题。看看get_serializer_context这里的默认实现https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/generics.py以了解更多信息。希望能帮助到你..

编辑 由于您PostReplySerializer在detail_route 中使用了不同的serializer(),因此需要创建如下的序列化器实例serializer = PostReplySerializer(replies, many=True, context={'request': self.request})

推荐阅读
落单鸟人
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有