Django: how to uses bulk_create (batch creation) to get the id after successful creation
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.
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:
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')