Reputation: 43
I have some Django fields, and here is what i'm trying to do.
I have a Times
field, a Price
Field and a Start Date
field.
So the User would input, for example:
Times = 12
Price = 100,00
Start Date = 2019-11-01
with those, the following lists are created:
Times = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
Price = [100,00, 100,00, 100,00, 100,00, 100,00, 100,00, 100,00, 100,00, 100,00, 100,00, 100,00, 100,00, ]
Start Date = [2019-11-01, 2019-12-01, 2020-01-01, 2020-02-01, 2020-03-01, 2020-04-01, 2020-05-01, 2020-06-01, 2020-07-01, 2020-08-01, 2020-09-01, 2020-10-01, 2020-11-01]
I already know how to create those lists, i'm struggling on how to insert them into Django's Database Table, one per line with the same ID or PK. Example -
Times Price Dates
1 100,00 2019-11-01
2 100,00 2019-12-01.....
Upvotes: 2
Views: 51
Reputation: 477065
You can construct these objects in a list, and then make a query to insert these in bulk, like:
MyModel.objects.bulk_create([
MyModel(time=time, price=price, start_date=start_date)
for time, price, start_date in zip(list_of_time, list_of_price, list_of_date)
])
If the number of objects is large, then creating these in "bulk" at the database side will result in a significant speedup.
Upvotes: 3
Reputation: 615
EDIT: renamed variables for better understanding
for t, p, sd in zip(times, prices, start_dates):
YourModel.objects.create(Times=t, Price=p, StartDate=sd)
Upvotes: 4