Getting Lists from QueryDicts - Django
I was writing recently writing a test for an API endpoint and discovered something interesting. Maybe it’s a noob mistake to not already know about this, but it caught me off guard.
I was passing the following dict into a request as POST parameters
data = { 'str_key': 'A string', 'list_key': ['List index 0', 'List index 2'] }
All looks normal when I print out my request.POST QueryDict.
request.POST >>> <QueryDict: {u'str_key': [u'A string'], u'list_key': [u'List index 0', u'List index 1']}>
Now I can use .get to retrieve they keys as such
request.POST.get('str_key') >>> u'A string'
However, something strange happens when I try and get the list. It only returns the last object in the list, as a string!
request.POST.get('list_key') >>> u'List index 1'
This confused me for a bit until I asked a few people and did some digging to discover that to retrieve lists from QueryDicts, you must use QueryDict.getlist. It worked!
request.POST.getlist('list_key') >>> [u'List index 0', u'List index 1']
I’m surprised that I had not encountered this situation before, but it’s a good reminder that a QueryDict isn’t quite a Dict! So use getlist to retrieve lists from QueryDicts!












