How to access query parameter in serializer django rest framework
I am trying to access query parameter in the serializer. I am not sure what I am doing wrong, I tried to follow a few solution.
class MyViewSet(viewsets.ModelViewSet):
.......
serializer_class = MySerializer
def get_serializer_context(self):
context = super().get_serializer_context()
context['test'] = "something"
return context
In my Serializer,
class MySerializer(serializers.ModelSerializer):
isHighlight = serializers.SerializerMethodField()
def get_isHighlight(self, obj):
print(self.context['test'])
return self.context['test']
I am getting this error,
Django Version: 3.2.7
Exception Type: KeyError
Exception Value: 'test'
Interestingly, I can see it can print the value in console and then the exception. I also tried to directly access the request variable like
class MySerializer(serializers.ModelSerializer):
isHighlight = serializers.SerializerMethodField()
def get_isHighlight(self, obj):
return self.context['request'].query_params['page']
But its showing the same error
Django Version: 3.2.7
Exception Type: KeyError
Exception Value: 'request'
Any suggestions? Thanks in advance.