Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django HTTP Request get vs getlist behavior

Tags:

python

django

I had a Django form that submitted a list of values to my view. I first tried retrieving the list using the get method but discovered that it only returned the last one and I should be using getlist. After some stumbling around I found a closed Django bug that explained the motivation for this behavior:

The reasoning behind this is that an API method should consistently return either a string or a list, but never both. The common case in web applications is for a form key to be associated with a single value, so that's what the [] syntax does. getlist() is there for the occasions (like yours) when you intend to use a key multiple times for a single value.

I'm just wondering whether this is actually a best practice - it contradicts the way the get method works on other data structures, ie. dictionaries.

like image 255
Dan Goldin Avatar asked Feb 04 '12 19:02

Dan Goldin


1 Answers

HTTP requests do support multiple values assigned to a one parameter (key). That's why people can use them and do (sometimes) use them. That's also why Django introduced the MultiValueDict structure.

Division into get() and getlist() is beneficial, because it helps you avoid errors and keeps your view code simple. Consider other behaviors, they all require more code to do exactly the same thing:

  • get() always returning list.

    In most use cases you pass just one value to a one key, so you would need to add [0] and provide default value as a list.

    param = request.GET.get('param', ['default value',])[0]

  • get() returning single value or a list, depending on number of values.

It is a drawback in HTML selects with multiple options allowed. People can select zero, one or more values. That means you'll need to convert single value to list or in opposite direction by yourself:

 params = request.GET.get('params', [])
 # Here you have absolutely no idea if this is a list or a single value
 # But you will need only one of that types

 # If you need list: ---------------------------------
 if not isinstance(params, list):
     params = [params,]

 objs = TestModel.objects.filter(id__in=params).all()

 # If you need single value: -------------------------
 if isinstance(params, list):
     params = params[0]   # Error if params is empty list...


obj = TestModel.objects.get(id=params)
  • get() always returning single value. So how do you handle multiple values without getlist in that case?

So to answer your question there is an added value of get/getlist behaviour.

like image 89
Mariusz Jamro Avatar answered Sep 30 '22 20:09

Mariusz Jamro