本文介绍了如何从Django的请求获取多值密钥的所有值.GET QueryDict的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Django文档在 QueryDict.iteritems()使用与 QueryDict .__ getitem __()相同的最后一个逻辑值,这意味着如果该键具有多个值,则 __ getitem __()返回最后一个值。



让我们说 print request.GET 看起来像这样:



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



如果我想要得到一个像因为 > iteritems 上面提到的行为:

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

获得没有太多循环的结果的最有效的方法是什么?





我应该提到我不是诉诸 QueryDict.urlencode()因为该请求中有一些键,我不希望在字符串中。我可以改变字符串,并把这些key = value,但只是想知道是否有更好的方法来解决这个问题。我明白这个信息应该被明确提到。

解决方案

这应该是有效的:

  mstring = [] 
for request.GET.iterkeys():#for key in request.GET也可以。
#在这里添加过滤逻辑。
valuelist = request.GET.getlist(key)
mstring.extend(valuelist中val的['%s =%s'%(key,val)])
print'& '.join(mstring)


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.

解决方案

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)

这篇关于如何从Django的请求获取多值密钥的所有值.GET QueryDict的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-24 20:05