Transaction atomic needed for bulk create?

Question:

I’m using the bulk_create method from Django to create many entries at once.

To ensure that the changes are only committed if there is no exception I’m thinking about adding transaction.atomic() to the code blocks but I’m not sure if I need to add it.

From my understanding I only need to add it in Scenario 2 because in this case I’m executing more than one query.

Scenario 1

Create 1.000 entries in one query

Entry.objects.bulk_create([
    Entry(headline='This is a test'),
    Entry(headline='This is only a test'),
    # ...
])

Scenario 2

Create 10.000 entries in in batches of 1.000

Entry.objects.bulk_create([
    Entry(headline='This is a test'),
    Entry(headline='This is only a test'),
    # ...
], batch_size=1_000)
Asked By: Nepo Znat

||

Answers:

No, you don’t have to for either scenario. According to the Django source code, using transaction atomic would be redundant for bulk_create as that method already uses atomic transactions.

Answered By: Josh C
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.