2๐
โ
-
Yes, your approach is pretty much right and it will acquire the lock for the first query and the rest will have to wait until the transaction is complete.
-
If you are not using the version field for anything other than acquiring the lock, you can forcefully acquire a lock by forcefully evaluating the QuerySet using a
list()
. See the code below.@atomic_transaction def func(product_id, amount_to_purchase): # Forcefully acquiring a lock product = list(Product.objects.select_for_update.filter(...))[0] if product.amount_available_for_purchase > amount_to_purchase: # do payment related stuff Purchase.objects.create(product=product, amount=amount_to_purchase) # do more stuff
Here you are acquiring the lock forcefully by evaluating the QuerySet like mentioned here in the docs.
๐คPSN
Source:stackexchange.com