Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i set query parameter dynamically to request.GET in Django

OVERVIEW


A url with query parameters looks like.

http://example.api.com/search/?name=jhon&age=26

and on view if i am using django-filter all parameters are automatically extracted from request and it will return a filtered query-set .

views.py

class SearchView(TemplateView):
   template_name = "search.html"

   def get_queryset(self):
       return SearchFilter(request.GET, queryset=Model.objects.all()).qs

   def get_context_data(self, **kwargs):
      context = super(SearchView, self).get_context_data(**kwargs)
      return context

If i want to extract it manually from request.GET i can do.

def get_queryset(self):
   # extracting query parameter 
   q = self.request.GET.get('name')

PROBLEM STATEMENT


My search url looks like

 http://example.api.com/search/jhon-26

I am doing this because i don't want to reveal keys like 'name' and 'age' to public, this is for security abstraction these are the column of my db table .

I am getting jhon-26 in **kwargs, I want to split it and set as query parameter to request.GET so that my filter class will work fine

QUESTION


Is there anything to set attribute to request.GET?

# may be any set function available for this
self.request.GET.set('name', 'jhon')

How can i achieve this.

like image 822
Satendra Avatar asked Jul 19 '17 11:07

Satendra


1 Answers

I found solution to set query parameters to request.GET here

As request.GET QueryDict instance is immutable so we can not modify it directly so for that we need to set its _mutable property to True

if not request.GET._mutable:
   request.GET._mutable = True

# now you can edit it
request.GET['name'] = 'jhon'
request.GET['age'] = 26
like image 157
Satendra Avatar answered Sep 19 '22 01:09

Satendra