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?

Was it helpful?

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.

OTHER TIPS

According to the docs you want to use self.request.QUERY_PARAMS

You can see it being used here

UPDATE:

As of DRF 3.0:

The usage of request.QUERY_PARAMS is now pending deprecation in favor of the lowercased request.query_params

self.context['request'].query_params

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top