Bulk create model objects in django

Viewed 194388

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?

10 Answers
name = request.data.get('name')
period = request.data.get('period')
email = request.data.get('email')
prefix = request.data.get('prefix')
bulk_number = int(request.data.get('bulk_number'))

bulk_list = list()
for _ in range(bulk_number):
    code = code_prefix + uuid.uuid4().hex.upper()
    bulk_list.append(
        DjangoModel(name=name, code=code, period=period, user=email))

bulk_msj = DjangoModel.objects.bulk_create(bulk_list)

Check out this blog post on the bulkops module.

On my django 1.3 app, I have experienced significant speedup.

bulk_create() method is one of the ways to insert multiple records in the database table. How the bulk_create()

**

Event.objects.bulk_create([ Event(event_name="Event WF -001",event_type = "sensor_value"), Entry(event_name="Event WT -002", event_type = "geozone"), Entry(event_name="Event WD -001", event_type = "outage") ])

**

Related