2

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(....)
1
  • It is not per se one database query: this calls .save(..) behind the curtains, so it can result in more queries. Commented Oct 29 at 11:16

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.