bulk_create django code example

Example 1: how to save bulk create in django

# took 0.47 seconds
def builtin():
    insert_list = []
    for i in range(10000):
        name="String number %s" %i
        insert_list.append(Record(name=name))
    Record.objects.bulk_create(insert_list)

Example 2: bulk create django

bulk_create(objs, batch_size = None, ignore_conflicts = False)

#eg
Entry.objects.bulk_create([
...     Entry(headline='This is a test'),
...     Entry(headline='This is only a test'),
... ])
# inserts in one query (usually), caveats below:
# doesn't signal pre_save and post_save 
# cant use child models
# no many-to-many
# obj list fully evaluates if objs is a generator

Example 3: django bulk update

objs = [
    Entry.objects.create(headline='Entry 1'),
    Entry.objects.create(headline='Entry 2'),
]
objs[0].headline = 'This is entry 1'
objs[1].headline = 'This is entry 2'
Entry.objects.bulk_update(objs, ['headline'])

# Caveats #
# -You cannot update the model’s primary key.
#
# -Each model’s save() method isn’t called, and the pre_save and post_save signals aren’t 
# sent.
#
# -If updating a large number of columns in a large number of rows, the SQL 
# generated can be very large. Avoid this by specifying a suitable batch_size.
#
# - Updating fields defined on multi-table inheritance ancestors will incur an extra query per ancestor.
# If objs contains duplicates, only the first one is updated.

Example 4: django insert bulk data

Entry.objects.bulk_create([
  Entry(headline = "foo"),
  Entry(headline = "bar")
])