← Back to Django, page 1

django-0019 · Medium mid

What are F() expressions in Django, and how do they help avoid race conditions?

F("field") refers to a column's value inside the database instead of a Python value. obj.copies = F("copies") - 1 or Model.objects.filter(...).update(copies=F("copies") - 1) makes the database do the arithmetic in one UPDATE, so two simultaneous requests cannot overwrite each other's change. F() also compares two fields in one row, for example filter(score__gt=F("pass_mark")).

Full answer

The classic bug is a read-modify-write in Python:

python
book = Book.objects.get(pk=1)
book.copies = book.copies - 1
book.save()

If two librarians issue the last copies at the same moment, both requests read copies = 5, both compute 4 and both save 4. One loan is lost. This is a race condition: the result depends on timing.

F() moves the calculation into SQL:

python
Book.objects.filter(pk=1).update(copies=F("copies") - 1)

This runs UPDATE book SET copies = copies - 1 WHERE id = 1. The database applies each update atomically, so two requests give 3, as expected.

On an instance, book.copies = F("copies") - 1; book.save() does the same. In Django 5.2, after saving, the attribute still holds the expression, not a number, so call book.refresh_from_db() before reading it, and saving the same instance again applies the expression a second time. Django 6.0 refreshes fields assigned expressions after save() on databases that support RETURNING (PostgreSQL, SQLite, Oracle), but refresh_from_db() remains the portable habit.

Other uses:

  • Compare columns: Student.objects.filter(score__gte=F("pass_mark"))
  • Annotate: .annotate(percent=F("score") * 100 / F("max_score"))
  • Order with null handling: .order_by(F("rank").asc(nulls_last=True))

Add a guard to avoid going negative: filter(pk=1, copies__gt=0).update(...) and check the returned row count. If 0 rows changed, there was no copy left. For multi-step logic where you must read and then decide, use select_for_update() inside a transaction.

python
import sys
import types

import django
from django.conf import settings

# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__

settings.configure(
    SECRET_KEY="demo-only-key-not-for-production",
    ALLOWED_HOSTS=["testserver"],  # the host name used by Django's test client
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

from django.db import models, connection
from django.db.models import F


class Book(models.Model):
    title = models.CharField(max_length=60)
    copies = models.IntegerField()
    class Meta:
        app_label = "school"


with connection.schema_editor() as editor:
    editor.create_model(Book)

Book.objects.create(title="Train to Pakistan", copies=2)

# Two "requests" both read the old value first (the race)
r1 = Book.objects.get(pk=1)
r2 = Book.objects.get(pk=1)
r1.copies -= 1; r1.save()
r2.copies -= 1; r2.save()
print("read-modify-write result:", Book.objects.get(pk=1).copies, "(should be 0)")

# Reset and do it with F() instead
Book.objects.filter(pk=1).update(copies=2)
for _ in range(2):
    Book.objects.filter(pk=1).update(copies=F("copies") - 1)
print("F() result:", Book.objects.get(pk=1).copies)

# Guarded issue: only succeeds while a copy is left
changed = Book.objects.filter(pk=1, copies__gt=0).update(copies=F("copies") - 1)
print("rows changed when none left:", changed)

b = Book.objects.get(pk=1)
b.copies = F("copies") + 5
b.save()
print(type(b.copies).__name__)
b.refresh_from_db()
print("after refresh:", b.copies)

Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. The 'race' is simulated by reading twice before either save, which is what concurrent requests do. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): read-modify-write result: 1 (should be 0) F() result: 0 rows changed when none left: 0 CombinedExpression after refresh: 5

Key points

  • F() refers to a column value inside SQL
  • update(field=F(field) + n) is atomic per row
  • After save() with F(), refresh_from_db() before reading (automatic in Django 6.0 on RETURNING databases)
  • F() compares two columns in one filter
  • A conditional update plus row count is a simple stock guard

Common mistakes

  • Doing read-modify-write in Python for counters and stock
  • Reading an attribute right after saving an F() expression
  • Saving the same instance twice and applying the expression twice
  • Not checking update()'s row count when using a guard condition

Follow-ups

  • When is F() not enough and you need select_for_update()?
  • How would you implement a 'likes' counter that gets thousands of hits per minute?
  • Does update() call save() or send post_save signals?

Tips

  • Describe the lost update with two concrete requests
  • Show the SQL that F() produces
  • Mention that update() skips save() and signals