[Django]-Bulk create model objects in django

79๐Ÿ‘

โœ…

Use bulk_create() method. Itโ€™s standard in Django now.

Example:

Entry.objects.bulk_create([
    Entry(headline="Django 1.0 Released"),
    Entry(headline="Django 1.1 Announced"),
    Entry(headline="Breaking: Django is awesome")
])
๐Ÿ‘คDanil

132๐Ÿ‘

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

๐Ÿ‘คecbtln

8๐Ÿ‘

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)
๐Ÿ‘คYagmur SAHIN

5๐Ÿ‘

worked for me to use manual transaction handling for the loop(postgres 9.1):

from django.db import transaction
with transaction.atomic():
    for item in items:
        MyModel.objects.create(name=item.name)

in fact itโ€™s not the same, as โ€˜nativeโ€™ database bulk insert, but it allows you to avoid/descrease transport/orms operations/sql query analyse costs

๐Ÿ‘คThorin Schiffer

4๐Ÿ‘

Here is how to bulk-create entities from column-separated file, leaving aside all unquoting and un-escaping routines:

SomeModel(Model):
    @classmethod
    def from_file(model, file_obj, headers, delimiter):
        model.objects.bulk_create([
            model(**dict(zip(headers, line.split(delimiter))))
            for line in file_obj],
            batch_size=None)
๐Ÿ‘คIvan Klass

3๐Ÿ‘

Using create will cause one query per new item. If you want to reduce the number of INSERT queries, youโ€™ll need to use something else.

Iโ€™ve had some success using the Bulk Insert snippet, even though the snippet is quite old.
Perhaps there are some changes required to get it working again.

http://djangosnippets.org/snippets/446/

๐Ÿ‘คOmerGertel

2๐Ÿ‘

Check out this blog post on the bulkops module.

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

๐Ÿ‘คMrJ

-29๐Ÿ‘

The easiest way is to use the create Manager method, which creates and saves the object in a single step.

for item in items:
    MyModel.objects.create(name=item.name)
๐Ÿ‘คDaniel Roseman

Leave a comment