Django transaction.atomic() on single operation prevents race conditions?

Why I need to use atomic() when I have only 1 db operation inside atomic block? My AI-assistant tells me that it prevents race conditions, but I don't use select_for_update() inside. It tells that db looks on unique constraints and sets lock automatically but only when I use atomic(), but if I will use it without atomic() race conditions can be happened.

Is it true? Can you explain this behaviour? I don't understand how it works if I have only one db operation inside.

Code example:

with atomic():
    Model.objects.create(....)

Django's .create(…) [Django-doc] does not per se work with one query.

Acutally what you do with .create(…) is you make a model instance with the same parameters, and then you call .save(…) [Django-doc] on it, with force_insert=True [Django-doc].

But the model itself can thus start to make additional queries, and therefore the it is not guaranteed that this is an atomic operation.

Вернуться на верх