Friday, June 7, 2013

Bulk model objects creation in Django

Have you ever thought about creating a list of model objects in one query (through Django ORM of-course)? It's really fast! Bumb, and everything are in the db.

Usually, we create and save objects in the db by calling:

from my_project.my_app import models

my_first_obj = models.MyModel(my_attr='genius')
my_first_obj.save()

my_second_obj = models.MyModel(my_attr='super')
my_second_obj.save()

Remember the objects are still not save in the database if we do not call 'save()'. The 'save()' is actually the method that communicate (query) with the underlying DBMS. And it takes time to insert object to the db. If the number of objects you have to create is hundreds or thousands, It'll be a really problem. With Django ORM API, we can create all the objects in a single action:

my_first_obj = models.MyModel(my_attr='genius')
my_second_obj = models.MyModel(my_attr='super')
obj_list = [my_first_obj, my_second_obj]
created_objs = models.MyModel.objects.bulk_create(obj_list)

The returned 'created_objs' is a list of created objects.