Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transaction atomic needed for bulk create?

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)
like image 846
Nepo Znat Avatar asked Feb 18 '20 16:02

Nepo Znat


People also ask

What does transaction atomic do in Django?

atomic allows us to create a block of code within which the atomicity on the database is guaranteed. If the block of code is successfully completed, the changes are committed to the database. If there is an exception, the changes are rolled back.

What is atomic transaction in operating system?

An atomic transaction is an indivisible and irreducible series of database operations such that either all occurs, or nothing occurs. A guarantee of atomicity prevents updates to the database occurring only partially, which can cause greater problems than rejecting the whole series outright.

Is Django Bulk_create atomic?

According to the Django source code, using transaction atomic would be redundant for bulk_create as that method already uses atomic transactions.

What is bulk create in Django?

Single or multiple records can be inserted into the database tables by writing a script. bulk_create() method is one of the ways to insert multiple records in the database table. How the bulk_create() method is used to insert the multiple data in a Django database table will be shown in this tutorial.


1 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.

like image 165
Josh C Avatar answered Oct 26 '22 00:10

Josh C