Django请求GET参数值列表 [英] Django request GET parameter value list

查看:41
本文介绍了Django请求GET参数值列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想进行一些排序,我想做的是使用这样的名为ordering的参数进行GET请求,并且该值将是我将用来进行如下排序的模型属性:

I want to do some sorting and what I have mind is doing a GET request with a parameter named ordering like this and the value will be the model atttribute that I will use to sort like this:

?order=['-age', 'height']

问题是当我尝试接收订单参数时.值是一个列表.

the problem is when I try to receive the order parameter.. The value is a list.

我尝试像这样使用ast:

I tried using the ast like this:

if 'order' in request.GET:
        import ast
        order = ast.literal_eval(request.GET.get('order'))
        queryset = queryset.order_by(*order)

有效.但是,我想避免使用ast库,还有其他方法吗?

It worked. However, I would like to avoid using the ast library, is there any other way around?

更新

我做了这样的参数:

?order =-年龄,身高

?order=-age,height

并且像这样在python中使用了split:

And just used split in python like this:

if 'order' in request.GET:
    order = request.GET.get('order').split(',')
    queryset = queryset.order_by(*order)

推荐答案

Django允许在请求中发送多个GET参数,但是您发送它们的方式是错误的(不仅是Django)
您要求的格式为?order = -age& order = height
然后在视图中可以执行 order_list = request.GET.getlist('order')

Django allows for multiple GET parameters to be sent in a request, but the way you're sending them is wrong (and not only for Django)
You request should be in the form ?order=-age&order=height
Then in the view you can do order_list = request.GET.getlist('order')

您无需检查键"order"是否在GET参数中,因为 .getlist()如果找不到该键,则返回一个空列表...

You don't need to check if the key 'order' is in the GET parameters as .getlist() returns an empty list if the key is not found...

如果只希望列表中的第一项,则可以使用 request.GET.get('order'),如果不存在该键,则返回None.

If you want only the first item from the list, you could use request.GET.get('order') which returns None if the key is not present.

最终代码:

order_list = request.GET.getlist('order')
queryset = queryset.order_by(*order_list)

PS 虽然django允许将GET参数命名为任何名称,但是PHP(我认为其他网络语言)要求GET列表参数命名为param [](示例order []),因此需要命名库像JQuery这样命名您的AJAX请求参数.在这种情况下,您将必须在视图中使用正确的名称,即 request.GET.getlist('order []')

P.S While django allows GET parameters to be named anything, PHP (and I think other web languages) require GET lists parameters to be named as param[] (example order[]) and therefore libraries like JQuery name your AJAX request params as such. In this case you will have to use the correct name in your view i.e request.GET.getlist('order[]')

这篇关于Django请求GET参数值列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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