30

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?

3 Answers 3

36

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.

Sign up to request clarification or add additional context in comments.

2 Comments

For newer versions: request.QUERY_PARAMS has been deprecated in favor of request.query_params since version 3.0, and has been fully removed as of version 3.2.
I would suggest using request.query_params.get('q') so it won't raise an exception.
9

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

You can see it being used here

DEPRECATED:

Prior to DRF 3.0:

The usage of request.QUERY_PARAMS is used and not the lowercased request.query_params

2 Comments

This is the error when i printed this command 'OneZeroSerializer' object has no attribute 'request'. I think this can be use in viewset not for Serializer Class
Ah yes, misread what was going on. Serializers aren't tied to requests, you can use them separately if you so chose. These means they have no concept of GET and POST data. You need to modify your view to send the query params to the serializer.
5

self.context['request'].query_params

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.