Home > Back-end >  Best practice for calling save() many times
Best practice for calling save() many times

Time:04-20

When calling save many times, it works but takes a few minuts.

num = 100000
for i in range(num):
    lu = sm.UserType(type_id=1)
    lu.save()

In my understanding save exec the SQL.

So if I can put save together, it takes a shorter time.

Is there any practice for this purpose?

CodePudding user response:

You can work with .bulk_create(…) [Django-doc]:

num = 100000

sm.UserType.objects.bulk_create([
    sm.UserType(type_id=1)
    for i in range(num)
])

This will for most databases create all records with one query, except for SQLite, that will create the objects in batches of 999 items.

  • Related