Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Django bulk_create return objects without pk?

Why does Django bulk_create return objects without pk's?

In [1]: item_list = [Model(title=str(i)) for i in range(10)]
In [2]: objs = Model.objects.bulk_create(item_list)
In [3]: print(objs[0].pk)
None

In the result objs == item_list

What sense is there in this?

I mean, this method could return a result of the operation (i.e. True, or False, or something else), not this useless collection of objects that I already have.

like image 636
Alex Heretic Avatar asked Nov 11 '15 15:11

Alex Heretic


1 Answers

Quoting from the django doc:

If the model’s primary key is an AutoField it does not retrieve and set the primary key attribute, as save() does.

According to django, it creates a list of database records in one shot, but the objects' ids are not retrieved. I think it's good for the situation where you do large insertions without further processing the data.

like image 114
Shang Wang Avatar answered Oct 12 '22 11:10

Shang Wang