Hey A’chille,

Django is working with auto commit set to True by default. If you only execute a single command you don’t need to explicitly open a database transaction. In the code you posted the context is not neccessary and the balance will be updated properly based on the current value stored in the database.

1- How can another session updates the balance when the it’s still locked?

You didn’t lock the object. The resulting SQL from the code you posted is:

UPDATE balance SET balance = balance + 100;

If you need to execute more than one command in the transaction and make sure it’s atomic, for example, adding a balance record as explained in the article — you need to use the db_transaction explicitly and lock the object using select_for_update.

2- What happens while the resource is locked, I mean Django-wise, does it, end the request, or wait for the lock to be released ?

If you lock the object and another session tried to lock it as well you will get a DatabaseError. If you want to wait for the other session to complete you can specify select_for_update(nowait=False) and the other session will wait. Keep in mind this is a blocking operation.


Full Stack Developer, Team Leader, Independent. More from me at https://hakibenita.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store