0

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?

whitebear
  • 11,200
  • 24
  • 114
  • 237
  • 2
    If you do not have any post_save/pre_save signals or custom save method you could use bulk_create – PTomasz Apr 19 '22 at 08:22
  • 3
    Use [bulk updates](https://stackoverflow.com/q/12661253/3929826) or a [transaction](https://docs.djangoproject.com/en/4.0/topics/db/transactions/). – Klaus D. Apr 19 '22 at 08:22

1 Answers1

5

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.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555