Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bulk create model objects in django

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?

like image 764
Alexis Métaireau Avatar asked Aug 31 '10 11:08

Alexis Métaireau


People also ask

What is bulk create Django?

Django bulk_create can help us optimize our application using a small number of database calls to save a lot of data. In other words, bulk_create can save multiple model instances into the database using only one database call.

What does Django bulk create return?

According to django, it creates a list of database records in one shot, but the objects' ids are not retrieved. I think it's good for the situation where you do large insertions without further processing the data.

How do I create a new model object in Django?

Creating objects To create an object, instantiate it using keyword arguments to the model class, then call save() to save it to the database. This performs an INSERT SQL statement behind the scenes. Django doesn't hit the database until you explicitly call save() . The save() method has no return value.


1 Answers

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

like image 180
ecbtln Avatar answered Oct 18 '22 05:10

ecbtln