Search code examples
pythondjangodictionaryrequestmutable

QueryDict list is not modified


I can't modify the list of a mutable QueryDict object:

copy_GET = QueryDict('a=1&a=2&a=3', mutable=True)
l = copy_GET.getlist('a')
l
[u'1', u'2', u'3']

l.append(u'4') # add a new value to the list
copy_GET.getlist('a') # but list is not modified
[u'1', u'2', u'3']

copy_GET # query dict is not modified
<QueryDict: {u'a': [u'1', u'2', u'3']}>

Solution

  • If you look at the implementation of getlist, you can see that it creates a new list each time it is called. Modifying the list won't alter the query dict.

    You can use setlist to set the key to the updated list.

    copy_GET = QueryDict('a=1&a=2&a=3', mutable=True)
    l = copy_GET.getlist('a')
    l.append(u'4')
    copy_GET.setlist('a', l)