Saving many Django objects with one large INSERT statement

Imagine that you have the following situation:

for i in xrange(100000):
  account = Account()
  account.foo = i
  account.save

Obviously, the 100,000 statements INSERTexecuted by Django will take some time. It would be better to combine all these INSERTinto one big one INSERT. Here is what I hope I can do:

inserts = []

for i in xrange(100000):
  account = Account()
  account.foo = i
  inserts.append(account.insert_sql)

sql = 'INSERT INTO whatever... ' + ', '.join(inserts)

Is there a way to do this with QuerySet, without manually creating all of these statements INSERT?

+3
source share
2 answers

You can use raw SQL.

Either Account.objects.raw()or using django.db.connection objects.

This may not be an option if you want to maintain an agnostic database.

http://docs.djangoproject.com/en/dev/topics/db/sql/

, , , , .

0

, @transaction.commit_manually .save() , .

@transaction.commit_manually
def your_view(request):
    try:
        for i in xrange(100000):
            account = Account()
            account.foo = i
            account.save()   
    except: 
        transaction.rollback()
    else:
        transaction.commit() 

, , , . , MySQL , , Django.

+7

All Articles