Reputation: 11
I've a model with 3 fields : packing_id, multiplier, cost_id. I've data for packing_id and multiplier in arrays
packing_id = ['1', '2', '3', '4']
multiplier = ['11', '21', '31', '41']
and cost_id will be same for these 4 entries. Database should look like:
packing_id multiplier cost_id
1 11 1
----------------|-----------|-------
2 21 1
----------------|-----------|-------
3 31 1
----------------|-----------|-------
4 41 1
----------------|-----------|-------
How can i insert in in Sqlite database in bulk without using for loop
Upvotes: 1
Views: 31
Reputation: 2443
Check Django's bulk_create
https://docs.djangoproject.com/en/2.0/ref/models/querysets/#bulk-create
And use some zip
magic https://docs.python.org/3.4/library/functions.html#zip
packing_id = ['1', '2', '3', '4']
multiplier = ['11', '21', '31', '41']
cost_id = [1, 1, 1, 1]
all_columns = zip(packing_id, multiplier, cost_id)
YourModel.objects.bulk_create([
YourModel(
packing_id=packing_id,
multiplier=multiplier,
cost_id=cost_id,
)
for packing_id, multiplier, cost_id in all_columns
])
Upvotes: 1