在Django中如何获取GET请求的值列表?

23

我有一个终端点

http://127.0.0.1:8000/auction/?status=['omn','aad']

我需要获取状态列表,因此我执行以下操作

print (request.GET.getlist('status'))

返回给我的是

[u"['omn','aad']"]

这是一个字符串列表的列表。

然后我使用 ast.literal_eval 将字符串列表转换为列表。是否有直接获取状态列表的方法?

5个回答

52

一开始就不要用那种格式发送。发送单个HTML的多个值的标准方式是多次发送该参数:

http://127.0.0.1:8000/auction/?status=omn&status=aad

当您使用request.GET.getlist('status')时,它将正确地向您提供['omn','aad']


1
虽然这在技术上是正确的,但使用JavaScript有些困难,因为许多库都需要参数对象。对象不能有多个键,并且通常会作为/auction/?status[]=omn&status[]=aad发送到Django,因此您需要像这样访问键值:request.GET.getlist('status[]') - Micheal J. Roberts
javascript包query-string可以帮助解决这个问题(https://www.npmjs.com/package/query-string):`queryString.parse('foo[]=1&foo[]=2&foo[]=3', {arrayFormat: 'bracket'});` - kristian

6

深入解释@DanielRoseman的答案。

正确的方式是按照以下描述传递每个变量:http://127.0.0.1:8000/auction/?status=omn&status=aad

然而,如果您使用现代JavaScript框架(Vue、Angular、React),那么很有可能您将作为对象传递参数(例如,如果您正在使用axios、VueResource等)。因此,这是一个解决办法:

前端:

let params = {
   status: ['omn', 'aad',]
}

return new Promise((resolve, reject) => {
  axios.get(`/auction/`, { params: params }, }).then(response => {
      resolve(response.data);
  }).catch(error => {
      resolve(error.response);
  });
});

接下来,它将作为以下URL分派到Django:
[05/Aug/2019 10:04:42] "GET /auction/?status[]=omn&status[]=aad HTTP/1.1" 200 2418

接下来在相应的视图中可以这样获取:

# Before constructing **parameters, it may neccessary to filter out any supurfluous key, value pair that do not correspond to model attributes:
parameters['status__in'] = request.GET.getlist('status[]')

# Using parameters constructed above, filter the Auctions for given status:
auctions = Auction.objects.filter(is_active=True)

auctions = auctions.filter(**parameters)

4

request.GET['status'] 会返回 ['omn', 'aad']


1
工作了。非常感谢。但是,如果我在查询参数中没有状态,这将失败。是否有一种类似于字典中的get方法的方式,例如dictionary.get('key') or None。在获取查询参数时,我可以使用类似的符号吗?不想使用try-except - Praful Bagai
2
如果您按照这种方式使用它,您将得到一个带有“['omn','aad']”的str对象。 如果您想要一个列表对象,请参阅Daniel Roseman的答案。 - wensiso

1
例如,如果您访问下面的URL:
https://example.com/?fruits=apple&fruits=orange

然后,您可以在views.py中按照下面的示例获取GET请求的值列表。*我的回答解释了如何在Django中获取POST请求的值列表,我的回答解释了如何在Django中获取GET请求的值列表。
# "views.py"

from django.shortcuts import render

def index(request):

    print(request.GET.getlist('fruits')) # ['apple', 'orange']
    print(request.GET.getlist('meat')) # []
    print(request.GET.getlist('meat', "Doesn't exist")) # Doesn't exist
    print(request.GET._getlist('fruits')) # ['apple', 'orange']
    print(request.GET._getlist('meat')) # []
    print(request.GET._getlist('meat', "Doesn't exist")) # Doesn't exist
    print(list(request.GET.lists())) # [('fruits', ['apple', 'orange'])]
    print(dict(request.GET)) # {'fruits': ['apple', 'orange']}
    print(request.META['QUERY_STRING']) # fruits=apple&fruits=orange
    print(request.META.get('QUERY_STRING')) # fruits=apple&fruits=orange

    return render(request, 'index.html')

然后,您可以在index.html中获取如下所示的GET请求的值列表:
{# "index.html" #}

{{ request.META.QUERY_STRING }} {# fruits=apple&fruits=orange #}

此外,如果您访问下面的网址:
https://example.com/?fruits=apple,orange

然后,您可以在views.py中按照下面的方式获取GET请求的值列表:
# "views.py"

from django.shortcuts import render

def index(request):

    print(request.GET['fruits'].split(',')) # ['apple', 'orange']
    print(request.GET.getlist('fruits')[0].split(',')) # ['apple', 'orange']
    print(request.GET._getlist('fruits')[0].split(',')) # ['apple', 'orange']
    print(list(request.GET.values())[0].split(',')) # ['apple', 'orange']
    print(list(request.GET.items())[0][1].split(',')) # ['apple', 'orange']
    print(list(request.GET.lists())[0][1][0].split(',')) # ['apple', 'orange']
    print(request.GET.dict()['fruits'].split(',')) # ['apple', 'orange']
    print(dict(request.GET)['fruits'][0].split(',')) # ['apple', 'orange']
    print(request.META['QUERY_STRING']) # fruits=apple,orange
    print(request.META.get('QUERY_STRING')) # fruits=apple,orange

    return render(request, 'index.html')

然后,您可以在index.html中获取如下所示的GET请求的值列表:
{# "index.html" #}

{{ request.GET.fruits }} {# apple,orange #}
{{ request.GET.dict }} {# {'fruits': 'apple,orange'} #}
{{ request.META.QUERY_STRING }} {# fruits=apple,orange #}

-4

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接