如何在Django中为同一参数使用多个变量处理request.GET [英] How to handle request.GET with multiple variables for the same parameter in Django

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

问题描述

在Django视图中,您可以访问 request.GET ['variablename'] ,因此在您看来,您可以执行以下操作:

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

myvar = request.GET['myvar']

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

<class 'django.http.QueryDict'>

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

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

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

您想为参数 myvar 返回python list ,然后执行类似的操作:

You would like a python list returned for the parameter myvar, then do something like this:

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

但是,当您尝试仅获得URL中传递的最后一个值时,即在上面的示例中,您将得到 567 ,则外壳中的结果将是:

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

但是,当您打印 request.GET 似乎有一个列表即:

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.


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

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)返回带有请求密钥的
数据,作为
Python列表。如果
密钥不存在,则返回一个空列表。保证
返回某种形式的列表

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.

更新:
如果有人知道django开发人员为什么这样做,请告诉我,这似乎违反直觉

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!

推荐答案

您想要 getlist() GET对象的功能:

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

request.GET.getlist('myvar')

这篇关于如何在Django中为同一参数使用多个变量处理request.GET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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