Django: how to uses bulk_create (batch creation) to get the id after successful creation

created at 07-16-2021 views: 3

environment

Django: how to uses bulk_create (batch creation) to get the id after successful creation

  • django=3.1
  • python=3.8

Ideas

For Postgres, you can directly use the bulk_create feature

list_of_objects = Category.objects.bulk_create([
    Category(headline="Django 2.0 Released"),
    Category(headline="Django 2.1 Announced"),
    Category(headline="Breaking: Django is awesome")
... ])

>>> list_of_objects[0].id
1

This method only works with Postgres, and this feature is supported since Django 1.10.

mysql solution

method 1: first extract all the ids, and then compare, the newly added id is the id created in batch

category_ids = Category.objects.values_list('id', flat=True)
categories = Category.objects.bulk_create([
    Category(title="title1", user=user, created_at=now),
    Category(title="title2", user=user, created_at=now),
    Category(title="title3", user=user, created_at=now),
])
new_categories_ids = Category.objects.exclude(id__in=category_ids).values_list('id', flat=True)

Disadvantages:

  1. The larger the table, the greater the overhead.
  2. If you create multiple batches at the same time, there will be confusion

method 2: add a field to the table as a mark for batch creation this time

import time
import random
flag= int(time.time())+random.randint(0,10000)

categories = Category.objects.bulk_create([
    Category(title="title1", user=user, flag=flag),
    Category(title="title2", user=user, flag=flag),
    Category(title="title3", user=user, flag=flag),
])

new_cats = Category.objects.filter(flag=flag).values_list('id')
Please log in to leave a comment.