这是我的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
.
它不在self.context中,因为您已覆盖get_serializer_context
。request
对象通过此方法附加到上下文。只需添加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})