Reputation: 7364
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.
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)
It worked. However, I would like to avoid using the ast library, is there any other way around?
UPDATE
I did my parameter like this:
?order=-age,height
And just used split in python like this:
if 'order' in request.GET:
order = request.GET.get('order').split(',')
queryset = queryset.order_by(*order)
Upvotes: 4
Views: 18282
Reputation: 2288
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')
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...
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.
Final code:
order_list = request.GET.getlist('order')
queryset = queryset.order_by(*order_list)
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[]')
Upvotes: 17