Manish Gupta Manish Gupta - 5 months ago 11
Ajax Question

multiple object querydict to lists

I am sending some javascript objects as array of objects to django view via ajax. The object is like:

[{'oid':'id1','oiid':'iid1'},{'oid':'id2','oiid':'iid2'}]


My ajax:

....
type : "POST",
data : {action:'pack_orders',
order_dict:$checkedRows},
....


I can see the request in django view as QueryDict like:

<QueryDict : {'order_dict[0][oid]':'id1','order_dict[0][oiid]':'iid1',
'order_dict[1][oid]':'id2','order_dict[1][oiid]':'iid2'}>


How can i get lists from querydict in django view like:

oid_list = ['id1','id2']
oiid_list = ['iid1','iid2']


Output in views.py:

{'order_dict[0][oid]':'id1','order_dict[0][oiid]':'iid1',
'order_dict[1][oid]':'id2','order_dict[1][oiid]':'iid2'}


EDIT:

1) Added views.py output from statement
print dict(request.POST)

Answer

I am not sure if you are sending order_dict after JSON.stringifying it. If not, I suggest do it. Accept it as json string in your view, do a json.loads() on it. Post this you have a list of dictionary.

Lets say you store it in variable called data, then you can do as following

oid_list = [x.get('oid') for x in data]
oiid_list = [x.get('oiid') for x in data]

Output:

oid_list - ['id1', 'id2']
oiid_list - ['iid1', 'iid2']

Should work for you. I dont know if its the best solution, but a simple one.