[Django]-Django request GET parameter value list

16👍

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

Leave a comment