I haven't seen any thing on this topic in Django's online documents.
I am trying to save a list of objects to database, but what I can do is loop through the list and call save() on every object.
So does Django hit database several times? Or Django will do one batch save instead?
To create multiple records based on a Django model you can use the built-in bulk_create() method. The advantage of the bulk_create() method is that it creates all entries in a single query, so it's very efficient if you have a list of a dozen or a hundred entries you wish to create.
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.
The . save() method is used to write a model instance to the database. It can be an existing record or even a new one. For an existing record, Django will run a SQL UPDATE statement on the database.
create() will automatically save, so even if you fix your error - you will still have to make sure the arguments to create fulfill the database requirements to save a record.
As of Django 1.4, there exists a bulk_create()
method on the QuerySet object, which allows for inserting a list of objects in a single query. For more info, see:
bulk_create
Unfortunately, batch inserts are something that Django 1.3 and prior do not directly support. If you want to use the ORM, then you do have to call save() on each individual object. If it's a large list and performance is an issue, you can use django.db.cursor to INSERT the items manually inside a transaction to dramatically speed the process up. If you have a huge dataset, you need to start looking at Database engine specific methods, like COPY FROM in Postgres.
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