Luis Sobrecueva
Luis Sobrecueva

Reputation: 690

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']}>

Upvotes: 1

Views: 689

Answers (3)

aircraft
aircraft

Reputation: 26924

I run into this issue, and my solution is:

mutable = query_params._mutable  # get out of the initial mutable
query_params._mutable = True
ip_list = query_params.pop('ip')
query_params._mutable = mutable # set the initial mutable 

Upvotes: 1

Alasdair
Alasdair

Reputation: 309099

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)

Upvotes: 2

anjaneyulubatta505
anjaneyulubatta505

Reputation: 11705

we can convert it to a mutable QueryDict instance by copying it:

request.GET = request.GET.copy()
# update querydict like
request.GET['hi'] = 'hello'

Upvotes: 0

Related Questions