F Expression (Django)
An F expression references a model field's value inside a query so the database does the computation. It lets you compare or update fields using their current column values without first loading them into Python.
Django
F() points at a column. Comparing two fields — filter(F('sales') > F('target')) — or updating relative to the current value — update(views=F('views') + 1) — happens entirely in SQL, which is both faster and free of race conditions.
The atomic-increment use is the classic example: post.objects.filter(pk=1).update(views=F('views') + 1) avoids the read-modify-write race where two requests both read the same count and one overwrites the other. The increment is done in a single UPDATE.
F expressions also work in annotate() and aggregate() to compute derived values (price * quantity) in the database, keeping heavy arithmetic off the Python side.
Syntax
from django.db.models import F
.update(count=F("count") + 1)Examples
Python
from django.db.models import F
# atomic increment (no race condition)
Post.objects.filter(pk=1).update(views=F("views") + 1)
# compare two columns
Product.objects.filter(stock__lt=F("reorder_level"))