[Django]-Saving many Django objects with one big INSERT statement

0👍

You could use raw SQL.

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

This might not be an option if you want to maintain database agnosticism.

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

If what you’re doing is a one time setup, perhaps using a fixture would be better.

8👍

As shown in this related question, one can use @transaction.commit_manually to combine all the .save() operations as a single commit to greatly improve performance.

@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() 

Alternatively, if you’re feeling adventurous, have a look at this snippet which implements a manager for bulk inserting. Note that it works only with MySQL, and hasn’t been updated in a while so it’s hard to tell if it will play nice with newer versions of Django.

Leave a comment