chefsmart
chefsmart

Reputation: 6981

how to obtain all values of a multi-valued key from Django's request.GET QueryDict

The Django docs say at http://docs.djangoproject.com/en/dev/ref/request-response/#django.http.QueryDict.iteritems thatQueryDict.iteritems() uses the same last-value logic as QueryDict.__getitem__(), which means that if the key has more than one value, __getitem__() returns the last value.

Let's say print request.GET looks like this:

<QueryDict: {u'sex': [u'1'], u'status': [u'1', u'2', u'3', u'4']}>

If I want to get a string like sex=1&status=1&status=2&status=3&status=4 (standard HTTP GET stuff) the following code won't give the desired results because of the iteritems behavior mentioned above:

mstring = []
for gk, gv in request.GET.iteritems():
    mstring.append("%s=%s" % (gk, gv))
print "&".join(mstring)

What is the most efficient way to obtain the result that I want without too much looping?

Regards.

[EDIT]

I should mention that I am not resorting to QueryDict.urlencode() because there are some keys in that request.GET that I don't want in the string. I could alter the string and take those key=value out, but just wondering if there is a better way to go about this. I realize this information should have been explicitly mentioned.

Upvotes: 23

Views: 34120

Answers (8)

JekR
JekR

Reputation: 21

To obtain all the values from one. It's better to use getlist("key", default=list). All the values from the key is stored in a list.

request.POST.getlist('key',default=list)

Upvotes: 2

mindsound
mindsound

Reputation: 1

There is a useful function in django http utils you can use:

>>> from django.utils.http import urlencode
>>> print(urlencode({"tag": [1, 2, 3], "sentence":2}, doseq=True))

'tag=1&tag=2&tag=3&sentence=2'

Upvotes: 0

Mark Lesly
Mark Lesly

Reputation: 21

It's easy! Just print(dict(request.GET))

Upvotes: 4

mossplix
mossplix

Reputation: 3865

you can cast the querydict into a dictionary

map(int,dict(request.GET)["status"])

Upvotes: 1

elo80ka
elo80ka

Reputation: 15845

This should work:

mstring = []
for key in request.GET.iterkeys():  # "for key in request.GET" works too.
    # Add filtering logic here.
    valuelist = request.GET.getlist(key)
    mstring.extend(['%s=%s' % (key, val) for val in valuelist])
print '&'.join(mstring)

Upvotes: 16

Daniel Roseman
Daniel Roseman

Reputation: 599796

request.GET.getlist('status')

Upvotes: 8

Ashok
Ashok

Reputation: 10603

request.META['QUERY_STRING']

will give the complete query string

or if you want to get the list of values for a given key ex: list of values for status then

request.GET.getlist('status')

Upvotes: 26

David
David

Reputation: 681

I believe QueryDict.urlencode achieves your desired outcome if all you want to do is print out the QueryDict then just

print request.GET.urlencode()

should do the trick. Let me know if you were trying to do something else and I'll try to help!

Upvotes: 8

Related Questions