Django中如何获取URL参数列表?

问题描述 投票:0回答:5

我有一个端点:

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

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

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

It returns me:

```lang-none
[u"['omn','aad']"]
```

which is a list of string of list.

I then use ast.literal_eval to convert string of list to list. Is there a direct method to get the list of status?
python django get url-parameters parameter-list
5个回答
51
投票

首先不要以这种格式发送。为单个 HTML 发送多个值的标准方法是多次发送参数:

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

当您使用

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


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']


0
投票

例如,如果您访问以下网址:

https://example.com/?fruits=apple&fruits=orange

然后就可以在

views.py
中获取参数,如下图:

# "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
中获取参数,如下图:

{# "index.html" #}

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

-4
投票

这里是 HTTPRequestHTTPResponse

的文档

请求响应对象

© www.soinside.com 2019 - 2024. All rights reserved.