Django Django

Why do `Q` and `F` exist when `filter()` already takes keyword arguments?

Dima Noi 15, 2026

Short Answer

Because keyword arguments can only say one kind of thing: this column equals that Python value, and all of them together. Q wraps a condition in an object you can combine with |, &, and ~, which is the only way to express OR and NOT inside a single query. F refers to a column rather than a value, so the database can compare two columns to each other or do arithmetic on one, instead of Python fetching the number, changing it, and sending it back. Both are expression objects that carry no data — they describe SQL to be built, and the database does the work.


How It Works

filter(status="booked", declared_kg__lt=95) has two fixed properties. The keyword arguments are combined with AND, always, because a Python call has no syntax for anything else. And each value on the right-hand side is an ordinary Python object that becomes a query parameter — a literal the database receives, never a reference to something in the table.

Q removes the first limit. It holds exactly the same lookups you would have written as keywords, but as an object, so Python's operators apply: | produces OR, & produces AND, ~ negates. Passing Q objects positionally to filter() lets one query express a condition that keyword arguments cannot describe at all. This also makes conditions composable — a function can build up a Q from user input and hand it back to be applied later.

F removes the second limit. F("declared_kg") compiles to the column name in the generated SQL, not to a value. So filter(actual_kg__gt=F("declared_kg")) becomes a WHERE clause comparing two columns, evaluated row by row inside the database. The alternative without F is to fetch every row and compare the two attributes in Python, which means transferring rows you will discard.

The same substitution works on the write side. update(actual_kg=F("actual_kg") + 10) compiles the addition into the SET clause, so the database reads the old value and writes the new one in a single statement. Nothing is read into Python first, which is why this is also the correct way to increment a counter that other processes might be touching — there is no window between a read and a write, because there is no separate read.

The general shape is worth naming: both classes turn something you would otherwise compute in Python into something the database computes. They are inert on their own — constructing a Q or an F touches nothing — and gain meaning only when a queryset compiles them into SQL.


Seeing It Run

These steps share a fixture. Create depot/models.py and bootstrap.py as shown in the first step, plus an empty depot/__init__.py, then replace main.py for each later step. Run with:

python3 main.py

Keyword arguments can only say AND

Three shipments, and the same query written three ways.

# depot/models.py
from django.db import models


class Shipment(models.Model):
    reference = models.CharField(max_length=20)
    status = models.CharField(max_length=20)
    declared_kg = models.IntegerField()
    actual_kg = models.IntegerField()


# bootstrap.py
import django
from django.conf import settings

settings.configure(
    DEBUG=True,
    INSTALLED_APPS=["depot"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
    DEFAULT_AUTO_FIELD="django.db.models.AutoField",
    USE_TZ=False,
)
django.setup()

from django.db import connection

from depot.models import Shipment


def seed():
    with connection.schema_editor() as editor:
        editor.create_model(Shipment)
    Shipment.objects.create(reference="SHP-4471", status="booked", declared_kg=100, actual_kg=120)
    Shipment.objects.create(reference="SHP-4408", status="held", declared_kg=300, actual_kg=290)
    Shipment.objects.create(reference="SHP-3157", status="booked", declared_kg=90, actual_kg=90)
    connection.queries_log.clear()


# main.py
from bootstrap import Shipment, seed
from django.db.models import Q

seed()

both = Shipment.objects.filter(status="booked", declared_kg__lt=95)
print("filter(a=..., b=...) :", sorted(both.values_list("reference", flat=True)))

either = Shipment.objects.filter(Q(status="held") | Q(declared_kg__lt=95))
print("Q(...) | Q(...)      :", sorted(either.values_list("reference", flat=True)))

not_booked = Shipment.objects.filter(~Q(status="booked"))
print("~Q(...)              :", sorted(not_booked.values_list("reference", flat=True)))

print("WHERE clause of the OR:", str(either.query).split("WHERE", 1)[1].strip())


filter(a=..., b=...) : ['SHP-3157']
Q(...) | Q(...)      : ['SHP-3157', 'SHP-4408']
~Q(...)              : ['SHP-4408']
WHERE clause of the OR: ("depot_shipment"."status" = held OR "depot_shipment"."declared_kg" < 95)


The keyword form returns only SHP-3157, the one shipment satisfying both conditions — that AND is not a choice, it is the only thing the syntax can mean. Swapping to Q(...) | Q(...) returns the two rows satisfying either, and the generated WHERE clause shows a real SQL OR rather than any post-filtering in Python. ~Q(status="booked") negates in the same way. These are not new lookups; they are the same lookups made combinable.

Note: str(queryset.query) interpolates parameters without quoting, so = held is a debugging view rather than runnable SQL.

Try it: Replace | with & in the line that builds either. The conditions are the same; what list do you get, and which word changes in the WHERE clause? The list is now [], and the clause becomes ("depot_shipment"."status" = held AND "depot_shipment"."declared_kg" < 95): the only held shipment has 300 kg declared. The Python operator between two Q objects literally becomes the SQL word between the two conditions.


F names a column, so the database compares columns

Replace main.py. Find every shipment whose actual weight exceeds what was declared — a comparison between two columns of the same row.

# main.py
from bootstrap import Shipment, connection, seed
from django.db.models import F

seed()

over = Shipment.objects.filter(actual_kg__gt=F("declared_kg"))
print("heavier than declared:", sorted(over.values_list("reference", flat=True)))
print("queries issued       :", len(connection.queries))
print("SQL:", connection.queries[-1]["sql"])


heavier than declared: ['SHP-4471']
queries issued       : 1
SQL: SELECT "depot_shipment"."reference" AS "reference" FROM "depot_shipment" WHERE "depot_shipment"."actual_kg" > ("depot_shipment"."declared_kg")


The WHERE clause names both columns, so the comparison happens per row inside the database and only the matching row travels back. Without F there is no way to express this in a filter at all — the right-hand side of a keyword lookup is always a value, and the value you want differs for every row. The fallback would be fetching all three shipments and comparing attributes in Python, which returns rows you then throw away.


F on the write side removes the read

Replace main.py. The same increment done twice: once by reading the value into Python, once by leaving it in the database.

# main.py
from bootstrap import Shipment, connection, seed
from django.db.models import F

seed()

shipment = Shipment.objects.get(reference="SHP-4471")
shipment.actual_kg = shipment.actual_kg + 10
shipment.save()
print("read, modify, save ->", len(connection.queries), "queries")

connection.queries_log.clear()
Shipment.objects.filter(reference="SHP-4408").update(actual_kg=F("actual_kg") + 10)
print("update with F      ->", len(connection.queries), "query")
print("SQL:", connection.queries[-1]["sql"])


read, modify, save -> 2 queries
update with F      -> 1 query
SQL: UPDATE "depot_shipment" SET "actual_kg" = ("depot_shipment"."actual_kg" + 10) WHERE "depot_shipment"."reference" = 'SHP-4408'


Two queries against one. The first version selects the row, adds ten in Python, and sends the result back — and between those two statements another process can write the same column, so its change is overwritten by a total computed from a stale read. The F version never reads: the addition is in the SET clause, the database applies it to whatever the current value is, and there is no window to lose an update in. That is the real argument for F on writes, with the saved round trip as a bonus.

Try it: Write the instance version with F() too: replace shipment.actual_kg = shipment.actual_kg + 10 with shipment.actual_kg = F("actual_kg") + 10, and after shipment.save() add print("in memory after save():", shipment.actual_kg). The attribute was given an expression, not a number; what will it print? You get 130, still in two queries. The addition was done by the database, inside the UPDATE, not by Python, and Django put the resulting value back on the object; the read-modify-write race is gone even though you went through save().


Edge Cases and Gotchas

  • Q objects must come before keyword arguments. filter(Q(...), status="booked") is valid; putting the keyword first is a SyntaxError from Python itself, not from Django.
  • ~Q and exclude() are not always the same on relations. Across a multi-valued relation, exclude() removes rows having any matching related row, while a negated Q inside filter() builds a different subquery — check the results rather than assuming.
  • F arithmetic respects database types. Dividing two integer columns performs integer division on most backends, so wrap one side in a float or use ExpressionWrapper with an explicit output_field when the result should not be truncated.
  • After saving with an F, refresh before reading. The attribute you assigned was an expression, and whether the instance shows the computed number afterwards has changed between Django versions — call refresh_from_db() and read a value you can trust.
  • F cannot cross to another table in a plain update. update() sets columns on one table only; comparing or combining with a related model's column needs annotate() first, or a Subquery.

Summary

Keyword arguments to filter() describe one shape of condition: column equals value, all ANDed. Q makes conditions into objects so they can be combined with OR and NOT, and F makes a column usable where a value would normally go, on both the read and the write side.

  • Keyword arguments are always combined with AND; Q with |, &, and ~ is the only way to express OR and NOT within one query.
  • Q objects hold the same lookups you would write as keywords, so they can be built up in one place and applied in another.
  • F("column") compiles to the column name, letting a WHERE clause compare two columns of the same row without fetching them.
  • update(x=F("x") + n) performs the arithmetic in the database in one statement, so no stale read can overwrite a concurrent change.
  • Both are inert objects until a queryset compiles them; constructing a Q or F touches the database not at all.

Trebuie să fii autentificat pentru a accesa laboratorul cloud.

Autentifică-te