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)
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.
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.
According to the Django source code, using transaction atomic would be redundant for bulk_create as that method already uses atomic transactions.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With