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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With