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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With