How can i access QueryString values in Serializer Django Rest Framework
-
21-12-2019 - |
Question
I am trying to access querystring values in serializer class.
class OneZeroSerializer(rest_serializer.ModelSerializer):
location = rest_serializer.SerializerMethodField('get_alternate_name')
def get_alternate_name(self, obj):
view = self.context['view']
print view.kwargs['q'] #output is {}
return 'foo'
class Meta:
model = OneZero
fields = ('id', 'location')
Views
class OneZeroViewSet(viewsets.ModelViewSet):
serializer_class = OneZeroSerializer
queryset = OneZero.objects.all()
Is this right way to access querystring?
Solution
When using ViewSets, you can access the request in the serializer context (like you access the view). You can access the query params from this
def get_alternate_name(self, obj):
request = self.context['request']
print request.QUERY_PARAMS['q']
return 'foo'
The attribute view.kwargs contains the named arguments parsed from your url-config, so from the path-part.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow