How to handle request.GET with multiple variables for the same parameter in Django

In the Django view, you can access request.GET['variablename'] , so in your opinion you can do something like this:

 myvar = request.GET['myvar'] 

Actual object type request.GET['myvar'] :

 <class 'django.http.QueryDict'> 

Now, if you want to pass several variables with the same parameter name, that is:

http://example.com/blah/?myvar=123&myvar=567

You want to return a python list for the myvar parameter, and then do something like this:

 for var in request.GET['myvar']: print(var) 

However, when trying to get only the last value passed to the URL, i.e. in the above example you will get 567 and the result in the shell will be:

 5 6 7 

However, when you type request.GET it seems like it has list i.e.

 <QueryDict: {u'myvar': [u'123', u'567']}> 



Ok Update: it is intended to return the last value, my use case I need a list.

from Django docs:

QueryDict. getitem (key) Returns the value for this key. If the key has more than one value, getitem () returns the last value. Raises django.utils.datastructures.MultiValueDictKeyError if the key does not exist. (This is a subclass of Python standard KeyError, so you can stick with a KeyError hook

QueryDict.getlist (key) Returns the data with the requested key as a Python list. Returns an empty list if the key does not exist. It is guaranteed to return some list.

Update: if someone knows why django dev did this, please let me know, it seems that showing the list is illogical, and it does not behave as one. Not very pythonic!

+61
django django-urls django-views
Oct 11 2018-10-11
source share
2 answers

You want the getlist () function of the GET object:

 request.GET.getlist('myvar') 
+145
Oct 11 2018-10-11
source share

Another solution is to create a copy of the request object ... Usually you cannot iterate over the request.GET or request.POST object, but you can do the following operations on the copy:

 res_set = request.GET.copy() for item in res_set['myvar']: item ... 
+1
Oct 22 '10 at 12:29
source share



All Articles