Concurrency fix 1: atomic update with F() expressions

Django Concurrency November 13, 2026 python

How do you fix a lost update with an atomic update using F() expressions?

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# ======================================================================
# Q: How do you fix a lost update with an atomic update using F() expressions?
# ======================================================================

from django.db.models import F

updated = (Product.objects
           .filter(pk=pk, stock__gte=qty)          # condition evaluated inside the database
           .update(stock=F('stock') - qty))        # UPDATE ... SET stock = stock - qty
if updated == 0:
    raise OutOfStock()