Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i access QueryString values in Serializer Django Rest Framework

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?

like image 605
Shoaib Ijaz Avatar asked Apr 11 '14 07:04

Shoaib Ijaz


People also ask

How do I get data from Django REST framework?

Django REST framework introduces a Request object that extends the regular HttpRequest, this new object type has request. data to access JSON data for 'POST', 'PUT' and 'PATCH' requests. However, I can get the same data by accessing request. body parameter which was part of original Django HttpRequest type object.

How do you get the context of a serializer?

To access the extra context data inside the serializer we can simply access it with "self. context". From example, to get "exclude_email_list" we just used code 'exclude_email_list = self. context.

How does serializer work on Django REST framework?

Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.

What is QuerySet in Django REST framework?

The root QuerySet provided by the Manager describes all objects in the database table. Usually, though, you'll need to select only a subset of the complete set of objects. The default behavior of REST framework's generic list views is to return the entire queryset for a model manager.


1 Answers

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.

like image 130
Denis Cornehl Avatar answered Sep 29 '22 22:09

Denis Cornehl