I have a Django view that processes a GET request. I want to rebuild the query string to include all variables except for one.
I was initially using list comprehension:
>>> from django.http import QueryDict >>> q = QueryDict('a=2&b=4&c=test') // <--- make believe this is request.GET >>> z = QueryDict('').copy() >>> z.update(dict([x for x in q.items() if x != 'b'])) >>> z.urlencode()
But I believe this may be a better solution:
>>> from django.http import QueryDict >>> q = QueryDict('a=2&b=4&c=test') // <--- make believe this is request.GET >>> z = q.copy() >>> del z['b'] >>> z.urlencode()
Can anyone think of an even better approach?
Django puts the GET request variables into a dictionary for you, so request.GET is already a QueryDict. You can just do this:
z = request.GET.copy() del z['a']
Note that dictionaries in python (and django QueryDicts) don’t have a del() method, you have to use python’s built in del() function. QueryDicts are immutable (but copies of them are not), so you were right to copy it before trying to delete from it. Also, in your last line z.urlencode() returns a string, it doesn’t convert z to a url encoded string, so you need to assign it to another variable in order to do something with it later.
Hope that helps