Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I recently looked for such a thing myself (inspired by <a href="http://docs.djangoproject.com/en/1.1/topics/db/queries/#topics-db-queries-update" rel="noreferrer">QuerySet.update()</a>, as I imagine you are too). To my knowledge, no bulk create exists in the current production framework (1.1.1 as of today). We ended up creating a custom manager for the model that needed bulk-create, and created a function on that manager to build an appropriate SQL statement with the sequence of VALUES parameters.</p> <p>Something like (apologies if this does not work... hopefully I've adapted this runnably from our code):</p> <pre><code>from django.db import models, connection class MyManager(models.Manager): def create_in_bulk(self, values): base_sql = "INSERT INTO tbl_name (a,b,c) VALUES " values_sql = [] values_data = [] for value_list in values: placeholders = ['%s' for i in range(len(value_list))] values_sql.append("(%s)" % ','.join(placeholders)) values_data.extend(value_list) sql = '%s%s' % (base_sql, ', '.join(values_sql)) curs = connection.cursor() curs.execute(sql, values_data) class MyObject(models.Model): # model definition as usual... assume: foo = models.CharField(max_length=128) # custom manager objects = MyManager() MyObject.objects.create_in_bulk( [('hello',), ('bye',), ('c', )] ) </code></pre> <p>This approach does run the risk of being very specific to a particular database. In our case, we wanted the function to return the IDs just created, so we had a postgres-specific query in the function to generate the requisite number of IDs from the primary key sequence for the table that represents the object. That said, it does perform significantly better in tests versus iterating over the data and issuing separate QuerySet.create() statements.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload