[Django]-Django CRUD operations for multiple records – transaction.atomic vs bulk_create

4👍

Transactions do generally speed up the inserting process. Since you are already in a transaction due to ATOMIC_REQUESTS = True, you won’t notice a difference when using @transaction.atomic(). The main reason transaction are faster is that committing takes time. Without a transaction, Django uses auto-commit mode, so every query results in a commit.

Transactions are not a magic bullet when it comes to performance. You are still performing 100 queries, and 100 roundtrips to the database. Even if your database runs on the same system, that is going to take some time. That’s where bulk_create comes into play. It performs a single query to insert all the data at once. You’ve just saved yourself 99 database roundtrips. That is way more significant than any speedup caused by transactions.

👤knbk

1👍

djangorestframework, right? I think you should improve your api function first:

def r_test(request):
    serializer = TestSerializer(data=request.data, many=True)
    if serializer.is_valid():
       serializer.save()

Try it again.

Leave a comment