Bulk create model objects in django

Alexis Métaireau picture Alexis Métaireau · Aug 31, 2010 · Viewed 122.2k times · Source

I have a lot of objects to save in database, and so I want to create Model instances with that.

With django, I can create all the models instances, with MyModel(data), and then I want to save them all.

Currently, I have something like that:

for item in items:
    object = MyModel(name=item.name)
    object.save()

I'm wondering if I can save a list of objects directly, eg:

objects = []
for item in items:
    objects.append(MyModel(name=item.name))
objects.save_all()

How to save all the objects in one transaction?

Answer

ecbtln picture ecbtln · Jan 17, 2012

as of the django development, there exists bulk_create as an object manager method which takes as input an array of objects created using the class constructor. check out django docs