32

I haven't seen any thing on this topic in Django's online documents.

I am trying to save a list of objects to database, but what I can do is loop through the list and call save() on every object.

So does Django hit database several times? Or Django will do one batch save instead?

zs2020
  • 53,766
  • 29
  • 154
  • 219

5 Answers5

38

As of Django 1.4, there exists a bulk_create() method on the QuerySet object, which allows for inserting a list of objects in a single query. For more info, see:

Gary
  • 3,425
  • 25
  • 18
  • Very nice! I should upgrade to 1.4 then. – netvope May 24 '12 at 19:42
  • bulk_create is awesome but, sadly it does not support inherited models. any idea to handle that? – Adiyat Mubarak Sep 24 '14 at 08:14
  • Note in particular that "[if the model’s primary key is an AutoField it does not retrieve and set the primary key attribute, as save() does, unless the database backend supports it (currently PostgreSQL)](https://docs.djangoproject.com/en/dev/ref/models/querysets/#bulk-create)". – Ninjakannon Jul 31 '17 at 21:46
10

Unfortunately, batch inserts are something that Django 1.3 and prior do not directly support. If you want to use the ORM, then you do have to call save() on each individual object. If it's a large list and performance is an issue, you can use django.db.cursor to INSERT the items manually inside a transaction to dramatically speed the process up. If you have a huge dataset, you need to start looking at Database engine specific methods, like COPY FROM in Postgres.

dbr
  • 165,801
  • 69
  • 278
  • 343
Brandon Konkle
  • 737
  • 5
  • 9
5

From Django 1.4 exists bulk_create(), but, always but.

You need to be careful, using bulk_create() it wont call instance save() method internally.

As django docs says

The model’s save() method will not be called

So, if you are overriding save method, (as my case was) you can't use bulk_create.

levi
  • 22,001
  • 7
  • 73
  • 74
2

This question is also addressed in How do I perform a batch insert in Django?, which provides some ways to make Django do this.

Community
  • 1
  • 1
Brian from QuantRocket
  • 5,268
  • 1
  • 21
  • 18
1

This might be a good starting point, but as the author of the code snippet says, it might not be production ready.

Gevious
  • 3,214
  • 3
  • 21
  • 42