TExcelTAD
Home › Django › Django Q & F Expressions

Django Q & F Expressions

Keyword arguments in filter() cover most queries, but they have two limits: conditions are always joined with AND, and the right-hand side is always a fixed value. Django's expression objects lift both limits:

  • Q objects describe conditions you can combine with | (OR), & (AND), ~ (NOT) and ^ (XOR).
  • F expressions refer to a column's value inside the database, so you can compare two fields or compute with them.

OR conditions with Q

python · try it yourself
import django
from django.conf import settings
settings.configure(DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}})
django.setup()
from django.db import models, connection
from django.db.models import Q

class Book(models.Model):
    title = models.CharField(max_length=50)
    genre = models.CharField(max_length=20)
    pages = models.IntegerField()
    year = models.IntegerField()
    class Meta:
        app_label = "demo"

with connection.schema_editor() as editor:
    editor.create_model(Book)
Book.objects.bulk_create([Book(title=t, genre=g, pages=p, year=y) for t, g, p, y in [
    ("Dune", "scifi", 412, 1965), ("Emma", "classic", 474, 1815),
    ("Hyperion", "scifi", 482, 1989), ("Ulysses", "classic", 730, 1922),
    ("Coraline", "fantasy", 162, 2002)]])

def titles(qs):
    return list(qs.order_by("id").values_list("title", flat=True))

print("scifi OR short:   ", titles(Book.objects.filter(Q(genre="scifi") | Q(pages__lt=200))))
print("NOT classic:      ", titles(Book.objects.filter(~Q(genre="classic"))))
print("(scifi|fantasy) & 1980+:",
      titles(Book.objects.filter((Q(genre="scifi") | Q(genre="fantasy")) & Q(year__gte=1980))))
print("Q + keyword:      ", titles(Book.objects.filter(Q(genre="classic") | Q(genre="scifi"), pages__gt=450)))
scifi OR short:    ['Dune', 'Hyperion', 'Coraline']
NOT classic:       ['Dune', 'Hyperion', 'Coraline']
(scifi|fantasy) & 1980+: ['Hyperion', 'Coraline']
Q + keyword:       ['Emma', 'Hyperion', 'Ulysses']

When you mix Q objects with keyword arguments in one call, the Q objects must come first.

Operator Meaning Example
Q(a) | Q(b) OR Q(genre="scifi") | Q(pages__lt=200)
Q(a) & Q(b) AND same as two keyword arguments
~Q(a) NOT ~Q(genre="classic")
Q(a) ^ Q(b) XOR (exactly one is true) Q(is_sale=True) ^ Q(is_new=True)

Building a search dynamically

Because Q objects are ordinary Python values, you can assemble a condition step by step — perfect for a search box where users can type several words:

python · try it yourself
import django, operator
from functools import reduce
from django.conf import settings
settings.configure(DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}})
django.setup()
from django.db import models, connection
from django.db.models import Q

class Article(models.Model):
    title = models.CharField(max_length=60)
    body = models.CharField(max_length=200)
    class Meta:
        app_label = "demo"

with connection.schema_editor() as editor:
    editor.create_model(Article)
Article.objects.bulk_create([
    Article(title="Django forms", body="Validate user input safely"),
    Article(title="Async Python", body="Event loops and coroutines"),
    Article(title="ORM tricks", body="Q objects make Django queries flexible"),
])

def search(text):
    words = text.split()
    conditions = [Q(title__icontains=w) | Q(body__icontains=w) for w in words]
    match_all = reduce(operator.and_, conditions)
    return list(Article.objects.filter(match_all).order_by("id").values_list("title", flat=True))

print(search("django"))
print(search("django queries"))
print(search("python loops"))
print(search("java"))
['Django forms', 'ORM tricks']
['ORM tricks']
['Async Python']
[]

Comparing fields with F

An F("field") refers to the value of another column in the same row. That lets the database compare or combine columns without loading anything into Python:

python · try it yourself
import django
from django.conf import settings
settings.configure(DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}})
django.setup()
from django.db import models, connection
from django.db.models import F

class Product(models.Model):
    name = models.CharField(max_length=30)
    stock = models.IntegerField()
    reorder_level = models.IntegerField()
    cost = models.DecimalField(max_digits=6, decimal_places=2)
    price = models.DecimalField(max_digits=6, decimal_places=2)
    class Meta:
        app_label = "demo"

with connection.schema_editor() as editor:
    editor.create_model(Product)
Product.objects.bulk_create([Product(name=n, stock=s, reorder_level=r, cost=c, price=p) for n, s, r, c, p in [
    ("Pen", 5, 20, "0.40", "1.00"), ("Notebook", 50, 10, "1.50", "3.20"),
    ("Stapler", 8, 8, "4.00", "3.50"), ("Ink", 30, 40, "2.00", "6.00")]])

low = Product.objects.filter(stock__lte=F("reorder_level")).order_by("name")
print("reorder:", [p.name for p in low])

loss = Product.objects.filter(price__lt=F("cost"))
print("sold at a loss:", [p.name for p in loss])

big_margin = Product.objects.filter(price__gte=F("cost") * 2).order_by("name")
print("price >= 2x cost:", [p.name for p in big_margin])
reorder: ['Ink', 'Pen', 'Stapler']
sold at a loss: ['Stapler']
price >= 2x cost: ['Ink', 'Notebook', 'Pen']

F in updates and annotations

F also works in update() (atomic increments, see Update Data) and in annotate(), which adds a computed column to every row:

python · try it yourself
import django
from django.conf import settings
settings.configure(DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}})
django.setup()
from django.db import models, connection
from django.db.models import F, ExpressionWrapper, DecimalField

class OrderLine(models.Model):
    item = models.CharField(max_length=30)
    quantity = models.IntegerField()
    unit_price = models.DecimalField(max_digits=6, decimal_places=2)
    class Meta:
        app_label = "demo"

with connection.schema_editor() as editor:
    editor.create_model(OrderLine)
OrderLine.objects.bulk_create([OrderLine(item=i, quantity=q, unit_price=u) for i, q, u in [
    ("Tea", 3, "4.50"), ("Cake", 2, "6.25"), ("Juice", 4, "2.00")]])

OrderLine.objects.filter(item="Juice").update(quantity=F("quantity") + 1)

lines = OrderLine.objects.annotate(
    total=ExpressionWrapper(F("quantity") * F("unit_price"),
                            output_field=DecimalField(max_digits=8, decimal_places=2))
).order_by("-total")

for line in lines:
    print(f"{line.item:<6} {line.quantity} x {line.unit_price} = {line.total:.2f}")
Tea    3 x 4.50 = 13.50
Cake   2 x 6.25 = 12.50
Juice  5 x 2.00 = 10.00

ExpressionWrapper tells Django which field type the computed value has, so it can convert the result back to Decimal.

Tip: Anything you can compute with F happens inside the database in a single query. That's faster than looping over objects in Python and avoids race conditions.

Test yourself

How do you find books that are scifi OR shorter than 200 pages?

  1. filter(genre="scifi", pages__lt=200)
  2. filter(Q(genre="scifi") | Q(pages__lt=200))
  3. filter(Q(genre="scifi") & Q(pages__lt=200))
  4. filter(genre="scifi").filter(pages__lt=200)

What does filter(stock__lte=F("reorder_level")) compare?

  1. stock with the string "reorder_level"
  2. Each row's stock with the same row's reorder_level
  3. stock with the average reorder level
  4. Nothing; it's invalid

Which operator negates a Q object?

  1. !
  2. -
  3. ~
  4. not