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

查看:35
本文介绍了如何在 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,并且 shell 中的结果将是:

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 时,它似乎有一个 list 即:

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.

来自 Django 文档:

from django docs:

QueryDict.getitem(键)退货给定键的值.如果键有多个值,getitem() 返回最后一个值.加注django.utils.datastructures.MultiValueDictKeyError如果密钥不存在.(这是一个Python 标准的子类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) 返回具有请求密钥的数据,作为蟒蛇名单.返回一个空列表,如果钥匙不存在.有保证返回某种列表.

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 开发人员为什么这样做,请告诉我,显示列表似乎违反直觉,而且它的行为不像一个.不是很pythonic!

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天全站免登陆