How to get primary keys of objects created using django bulk_create

mikec picture mikec · Apr 10, 2013 · Viewed 29.1k times · Source

Is there a way to get the primary keys of the items you have created using the bulk_create feature in django 1.4+?

Answer

Or Duan picture Or Duan · Sep 4, 2016

2016

Since Django 1.10 - it's now supported (on Postgres only) here is a link to the doc.

>>> list_of_objects = Entry.objects.bulk_create([
...     Entry(headline="Django 2.0 Released"),
...     Entry(headline="Django 2.1 Announced"),
...     Entry(headline="Breaking: Django is awesome")
... ])
>>> list_of_objects[0].id
1

From the change log:

Changed in Django 1.10: Support for setting primary keys on objects created using bulk_create() when using PostgreSQL was added