Leandro Lima
Leandro Lima

Reputation: 5438

Can I trust Django's bulk_create to preserve order?

When I do something like this:

model_list = [Model(name = 'First'), Model(name = 'Second'), Model(name = 'Third')]
Model.objects.bulk_create(model_list)

Can I trust that they will be created in that same order?

That is:

pk1 = Model.objects.get(name = 'First').pk
pk2 = Model.objects.get(name = 'Second').pk
pk3 = Model.objects.get(name = 'Third').pk

(pk3 > pk2) and (pk2 > pk1)

Upvotes: 7

Views: 2457

Answers (2)

David Vardanyan
David Vardanyan

Reputation: 66

Yes, you can trust according to the documentation for Django 4.2 here https://docs.djangoproject.com/en/4.2/ref/models/querysets/#bulk-create:

This method inserts the provided list of objects into the database in an efficient manner (generally only 1 query, no matter how many objects there are), and returns created objects as a list, in the same order as provided...

Upvotes: 2

catavaran
catavaran

Reputation: 45595

I think you can.

model_list = [Model(name = 'First'),
              Model(name = 'Second'),
              Model(name = 'Third')]
Model.objects.bulk_create(model_list)

This code will be translated to the following SQL:

INSERT INTO app_model (name) VALUES ('First'), ('Second'), ('Third')

It is very unlikely that regular SQL server will insert these rows in different order.

Upvotes: 4

Related Questions