如何在 Django 中处理具有同一参数的多个变量的 request.GET

在 Django 视图中,你可以访问 request.GET['variablename'],所以在你的视图中,你可以这样做:

myvar = request.GET['myvar']

实际的 request.GET['myvar']对象类型是:

<class 'django.http.QueryDict'>

现在,如果您想传递具有相同参数名称的多个变量,即:

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

您希望为参数 myvar返回一个 python list,然后执行以下操作:

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

但是,当您尝试只获得上面示例中在 url 中传递的最后一个值时,您将获得 567,shell 中的结果将是:

5
6
7

然而,当你打印 request.GET时,它看起来像是有一个 list,即:

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

更新: 它被设计为返回最后一个值,我的用例是我需要一个列表。

来自姜戈文档:

QueryDict.(咒语)(key) 报税表 给定键的值。如果 Key 有多个值, Gettem ()返回最后一个值 数据结构. MultiValueDictKeyError 如果密钥不存在。(这是一个 Python 标准的子类 键错误,所以你可以坚持捕捉 键错误

Getlist (key)返回 具有所请求键的数据,作为 返回一个空列表,如果 钥匙根本不存在,我保证 返回某种列表。

更新: 如果有人知道为什么 django 开发人员这样做,请让我知道,似乎违反直觉显示一个列表,它不像一个行为。不太像蟒蛇!

71703 次浏览

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

request.GET.getlist('myvar')

Another solution is creating a copy of the request object... Normally, you can not iterate through a request.GET or request.POST object, but you can do such operations on the copy:

res_set = request.GET.copy()
for item in res_set['myvar']:
item
...

When creating a query string from a QueryDict object that contains multiple values for the same parameter (such as a set of checkboxes) use the urlencode() method:

For example, I needed to obtain the incoming query request, remove a parameter and return the updated query string to the resulting page.

# Obtain a mutable copy of the original string
original_query = request.GET.copy()


# remove an undesired parameter
if 'page' in original_query:
del original_query['page']

Now if the original query has multiple values for the same parameter like this: {...'track_id': ['1', '2'],...} you will lose the first element in the query string when using code like:

new_query = urllib.parse.urlencode(original_query)

results in...

...&track_id=2&...

However, one can use the urlencode method of the QueryDict class in order to properly include multiple values:

new_query = original_query.urlencode()

which produces...

...&track_id=1&track_id=2&...