处理Django request.GET和多个变量的相同参数名称 [英] Handling Django request.GET and multiple variables for the same parameter name

查看:1242
本文介绍了处理Django request.GET和多个变量的相同参数名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在django视图等中,您可以访问 request.GET ['variablename'] ,所以在您看来,您可以返回执行以下操作:

  myvar = request.GET ['myvar'] 

实际请求.GET ['myvar']对象类型是:

 < class'django.http。的QueryDict'> 

现在,如果要传递与变量相同的多个变量,即



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



换句话说,您希望为参数返回一个python 列表 > myvar



本质上我想做的是这样的一个例子

  for request.GET ['myvar']:
print var

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



而shell中的结果将是:

  5 
6
7

但是,当您打印请求.GET似乎有一个列表ie:

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

Ok更新:
它旨在返回最后一个值,我的用例是我需要一个列表。



from django docs:


QueryDict。 getitem (key)
返回
给定键的值。如果
键有多个值,
getitem ()返回最后一个值。如果密钥不存在,则引发
django.utils.datastructures.MultiValueDictKeyError
。 (这是一个
子类的Python标准
KeyError,所以你可以坚持抓住
KeyError



QueryDict.getlist(key)以
Python列表的形式返回
数据,如果
不存在,返回一个空列表,保证
返回某种排序的列表

更新:
如果有人知道为什么django dev这样做了,请让我知道,似乎反直觉显示

解决方案

你想要 getlist()函数:

  request.GET.getlist('myvar')


In a django view etc. you can access the request.GET['variablename'], so in your view you can return do something like this:

myvar = request.GET['myvar']

The actual request.GET['myvar'] object type is:

<class 'django.http.QueryDict'>

Now, if you want to pass multiple variables with for the same parameter name i.e

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

In other words, you would like a python list returned for the parameter myvar

Essentially what i would like to do is something like this

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

However, when you try that you only get the last value passed in the url i.e in the example above you will get 567

and the result in the shell will be:

5
6
7

However, when you do a print of request.GET it seems like it has a list i.e:

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

Ok Update: It's designed to return the last value, my use case is i need a list.

from django docs:

QueryDict.getitem(key) Returns the value for the given key. If the key has more than one value, getitem() returns the last value. Raises django.utils.datastructures.MultiValueDictKeyError if the key does not exist. (This is a subclass of Python's standard KeyError, so you can stick to catching KeyError

QueryDict.getlist(key) Returns the data with the requested key, as a Python list. Returns an empty list if the key doesn't exist. It's guaranteed to return a list of some sort.

Update: If anyone knows why django dev's have done this please let me know, seems counter-intuitive to show a list and it does not behave like one. Not very pythonic!

解决方案

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

request.GET.getlist('myvar')

这篇关于处理Django request.GET和多个变量的相同参数名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆