简体   繁体   中英

Django bulk_create a list of lists

As the title indicates, is there a way to bulk_create list of lists. Like right now I bulk_create it like -

for i in range(len(x))   
  arr1 = []
    for m in range(len(y)):
    arr1.append(DataModel(foundation=foundation, date=dates[m], price=price[m]))
  DataModel.objects.bulk_create(arr1)

Now this will bulk create till the length of x.

Can it be done like so -

arr = []
for i in range(len(x))   
  arr1 = []
    for m in range(len(y)):
    arr1.append(DataModel(foundation=foundation, date=dates[m], price=price[m]))
  arr.append(arr1)
DataModel.objects.bulk_create(arr)

If not, what else can be done to store data faster?

Append your object to arr , not arr1 .
Or you can make flat list before bulk_create :

import itertools
arr = list(itertools.chain(*arr))

Try this....

arr = []
for i in range(len(x))   
  arr1 = []
    for m in range(len(y)):
    arr1.append(DataModel(foundation=foundation, date=dates[m], price=price[m]))
  #instead of appending the list, add list together to make one
  arr = arr + arr1
DataModel.objects.bulk_create(arr)

this will produce a single list of items process-able by bulk_create() method

reference: Python append() vs. + operator on lists, why do these give different results?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM