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
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.