DEV Community

Serhat Teker
Serhat Teker

Posted on • Originally published at tech.serhatteker.com on

Django - DB bulk_create()

bulk_create()

From Django doc:

This method inserts the provided list of objects into the database in an efficient manner (generally only 1 query, no matter how many objects there are):

So instead of inserting data into db one by one in an inefficient manner it is better to use this method.

Method api detail:

bulk_create(objs, batch_size=None, ignore_conflicts=False)
Enter fullscreen mode Exit fullscreen mode

Example:

>>> MyModel.objects.bulk_create([
...     MyModel(title='This is a test'),
...     MyModel(title='This is only an another test'),
... ])
Enter fullscreen mode Exit fullscreen mode

The batch_size parameter controls how many objects are created in a single query. The default is to create all objects in one batch, except for SQLite where the default is such that at most 999 variables per query are used.

On databases that support it (all except PostgreSQL < 9.5 and Oracle), setting the ignore_conflicts parameter(this parameter was added in Django 2.2) to True tells the database to ignore failure to insert any rows that fail constraints such as duplicate unique values. Enabling this parameter disables setting the primary key on each model instance (if the database normally supports it).

Another example for using python list comprehension to crate multi db model objects:

objs = [
    Message(
        name=e.name,
        subject=e.subject,
        content=e.content,
        sender_name=e.sender_name
    )
    for e in query_list
]
msg = Message.objects.bulk_create(objs=objs)

# or use it like below but it is better to explicitly
# assign the keyword arguments as above
# msg = Message.objects.bulk_create(objs)
Enter fullscreen mode Exit fullscreen mode

Important:

Please look at the number of caveats of this method in the documentation. Such as the model’s save() method will not be called, and the pre_save and post_save signals will not be sent.

All done!

Top comments (0)