Getting a KeyError for a "query" in a DRF serializer when using detail_route in my ViewSet

This is my 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) 

And this is my 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') 

The error indicates a line

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

and says:

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

Any idea why DRF says β€œquery” is a key mistake, although (in my opinion) should it be automatically in self.context ?

Please note that PostViewSet works fine for all other requests (if I receive a message, I get a list of messages, etc.). This just doesn't work for replies .

+6
source share
1 answer

This is not in self.context because you have redefined get_serializer_context . The request object is context bound using this method. Just add request: self.request to your return get_serializer_context statement to resolve the problem. Take a look at the standard get_serializer_context implementation here https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/generics.py to understand more. Hope this helps.

EDIT Because you are using a different serializer ( PostReplySerializer ) in detail_route, you need to instantiate a serializer, for example serializer = PostReplySerializer(replies, many=True, context={'request': self.request})

+4
source

All Articles