如何使用loop显示querydict

2024-05-26 07:47:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建一个函数来显示querydict的值和键。例如,如果我收到一个GET请求的QueryDict。

<QueryDict: {u'val1':[u'aa'],u'val2':[u'ab'],u'val3':[u'ac'],u'val4':[u'ad'], ... u'valn':[u'an'] ...}>

我现在的功能是这样的:

def displayQueryDicts(self, request):
    for x in request:
     print x # this will return the val1, val2, val3, val4, ..., valn
     print x .value() # I don't know how to print all the values

我现在的问题是,我怎样才能像这样打印这些值。。

val1   aa
val2   ab
val3   ac
val4   ad
...    ...
valn   an

Tags: the函数anabrequestadacaa
3条回答

注意,QueryDict只是一个类似字典的对象。有一个重要的区别。从docs

In an HttpRequest object, the GET and POST attributes are instances of django.http.QueryDict, a dictionary-like class customized to deal with multiple values for the same key. This is necessary because some HTML form elements, notably , pass multiple values for the same key.

如果要遍历请求的所有参数,并有多个具有相同键的参数,则需要在Python 3中使用QueryDict.lists(),或者在Python 2中使用QueryDict.iterlists()。请参阅output format的文档。

根据documentation

HttpRequest.GET

A dictionary-like object containing all given HTTP GET parameters.

您可以像在普通python上一样迭代它dict

for key, value in request.GET.iteritems():
    print "%s %s" % (key, value)

希望能有所帮助。

在python3中你可以

 for key, value in request.GET.items():
        print ("%s %s" % (key, value))

相关问题 更多 >