db.models.query.QuerySet.bulk_create()

bulk_create(objs, batch_size=None)

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):

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

This has a number of caveats though:

  • The model’s save() method will not be called, and the pre_save and post_save signals will not be sent.
  • It does not work with child models in a multi-table inheritance scenario.
  • 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).
  • It does not work with many-to-many relationships.
Changed in Django 1.9:

Support for using bulk_create() with proxy models was added.

Changed in Django 1.10:

Support for setting primary keys on objects created using bulk_create() when using PostgreSQL was added.

The batch_size parameter controls how many objects are created in 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.

doc_Django
2016-10-09 18:36:05
Comments
Leave a Comment

Please login to continue.