[Fixed]-Django 1.4 – bulk_create with a list

36👍

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]
👤jdi

5👍

>>> Entry.objects.bulk_create([
...     Entry(headline="Django 1.0 Released"),
...     Entry(headline="Django 1.1 Announced"),
...     Entry(headline="Breaking: Django is awesome")
... ])

You’re passing the ORM a list of instantiated objects in a list. Using this, and supposing that orig_list is a list of dictionaries,

>>> my_objects = [MyObject(a=x['a'], b=x['b']) for x in orig_list]
>>> MyObject.objects.bulk_create(my_objects)

1👍

Try this, and the point of bulk_create is to hit database only once, no matter how many you are creating. That’s why we consider it to be efficient.

class Entry(models.Model):
    name = models.CharField(max_length = 10)

a = ['test1', 'test2', 'test3', 'test4']

Entry.objects.bulk_create([Entry(name=x) for x in a])

—Edit—

Say you have a Model like this, in your models.py:

class Entry(models.Model):
    id = models.CharField(max_length = 10)

And you have a list like this (directly copied from your question):

list = ['abc', 'def', 'ghi']

Simply one line:

Entry.objects.bulk_create([Entry(id=x) for x in list])
👤xbtsw

Leave a comment