Haowei Cheng
Haowei Cheng

Reputation: 75

how to use the bulk_create() for many objects to do the save() operation

I have a lot of objects to save to the database, the code as below:

def addSthGroups(groups):
    for group in groups:  # each group is an object
        group.addSth()
        group.save()

and right now, it takes much time to save all of the object one by one. So my Question is: Is there a more efficient method to collect all of objects to just call the save() once, it may speed up the processing time, as I know, bulk_create sounds good to handle this scenario, can anyone give an example for this code? or any other good suggestion?

Upvotes: 6

Views: 9505

Answers (1)

Shang Wang
Shang Wang

Reputation: 25539

You can just do Group.objects.bulk_create(groups), assuming that Group is the model name.

bulk_create won't call save(). Quoting from django doc:

The model's save() method will not be called, and the pre_save and post_save signals will not be sent.

Upvotes: 15

Related Questions