How to past multiple list from ajax to Django

39 views Asked by At

I have an issue which I want to get all the data from list, so I want to loop every single data from selected items and insert it to database, currently it returns the data like this when I print it ['[object Object]', '[object Object]'], how can I insert these data one by one? or just print it one by one?

I have this list which is selected_items I loop the data and then pass it to ajax

selected_items = []; 
for (var i = 0; i < checkBoxes.length; i++) {        
     var selected_obj ={ 
        stock_id: checkBoxes[i].id,
        quantity: row.cells[3].innerHTML
      }
      selected_items.push(selected_obj);
}

when console the selected_items it's just like this

enter image description here

so now I want to pass these list to django using ajax

console.log(selected_items);
  $.ajax({
      type: "POST",
      url: "{% url 'sales-item' %}",
      data:{
        multiple_list: selected_items.join(','), item_size: selected_items.length
      }
  }).done(function(data){...

views.py

out_items = request.POST.getlist('multiple_list[]')
print(out_items)

and it prints like this

['[object Object]', '[object Object]']

Updated Code how can I loop the data? this is what I tried but it doesn't reflect the data at all

multiple_list: JSON.stringify(selected_items)

viesw.py

out_items = request.POST.get('multiple_list')

for i in out_items:
     print(out_items1[i])

**how to print or insert it to the database?

1

There are 1 answers

2
Nealium On

When you do selected_items.join(',') you are taking the __str__ (or js equivalent) of {'stock_id': 5, 'quantity': 15} which just happens to be [object Object]


So I'd recommend just using Json, which will encode the entire nested list-dict and will be loaded as a normal list-dict in python

Javascript

$.ajax({
    type: "POST",
    url: "{% url 'sales-item' %}",
    data:{
      multiple_list: JSON.stringify(selected_items),
      item_size: selected_items.length,
    }
}).done(function(data){...

Python

stock_list = json.loads(request.POST.get('multiple_list'))

print(type(stock_list))
# <class 'list'>

print(stock_list)
# [
#   {'stock_id': 5, 'quantity': 15},
# ]

Edit

Yes!, you'd just loop it like normal nested list-dict

stock_list = json.loads(request.POST.get('multiple_list'))

for stock_list_item in stock_list:
  obj, was_created_bool = MyModel.objects.get_or_create(
    stock_id=stock_list_item['stock_id'],
    quantity=stock_list_item['quantity']
  )

but! If you know you are going to be creating each item, I'd recommend using bulk_create

stock_list = json.loads(request.POST.get('multiple_list'))

bulk_create_list = []

for stock_list_item in stock_list:
  bulk_create_list.append(
    MyModel(  # Note: NO .object
      stock_id=stock_list_item['stock_id'],
      quantity=stock_list_item['quantity']
    )
  )

# Creates all items in one query
MyModel.objects.bulk_create(bulk_create_list)

& extra tidbit

These all work the same! (quite handy for dynamically creating filters ;) )

# setup
stock_list_item = {'stock_id': 5, 'quantity': 15}
# ----

MyModel.objects.get_or_create(
  stock_id=stock_list_item['stock_id'],
  quantity=stock_list_item['quantity']
)
# ==
MyModel.objects.get_or_create(**{'stock_id': 5, 'quantity': 15})
# ==
MyModel.objects.get_or_create(**stock_list_item)