I have a list, which I would like to bulk_create entries for in the database.
How can I do this without looping through the list, which I presume, would take away the point of bulk_create.
For example:
Instead of...
for x in list:
bulk_create...
How could I...
bulk_create for the entire list at once in an efficient manner
List contains:
list = ['abc', 'def', 'ghi']
It's simply a list of id's, not in the form that's ready to fed directly into bulk_create (not formatted with the entry fields). However, I suppose it would be possible to modify the list before passing it into bulk_create.
bulk_create
takes a list of objects as a single arg, in a single call. What you are doing in your example would be the same as looping and doing create()
Referencing: https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.bulk_create
aList = [
Entry(headline="Django 1.0 Released"),
Entry(headline="Django 1.1 Announced"),
Entry(headline="Breaking: Django is awesome")
]
Entry.objects.bulk_create(aList)
aList
refers to a list of objects that you already have instantiated and need to create in bulk with one query. If for instance you didn't already have that list of unsaved instances, and you had a list of values, you could then create your list with something like:
values = ['abc', 'def', 'ghi']
# a list of unsaved Entry model instances
aList = [Entry(headline=val) for val in values]
Or maybe you have a list of raw dictionary values that map to the model:
values = [{headline="abc"}, {headline="def"}, {headline="ghi"}]
aList = [Entry(**vals) for vals in values]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With