Django Filter & Field Lookups
filter() is the ORM's WHERE clause. You describe conditions as keyword arguments; Django builds safe, parameterized SQL. The keyword can be a plain field name (exact match) or a field name followed by a double underscore and a lookup, such as price__lt=10 or title__icontains="django".
All examples in this lesson use the same small product table:
| id | name | category | price | stock |
|---|---|---|---|---|
| 1 | Green Tea | drinks | 4.50 | 120 |
| 2 | Black Coffee | drinks | 3.00 | 0 |
| 3 | Rice Cracker | snacks | 2.25 | 40 |
| 4 | Dark Chocolate | snacks | 6.75 | 15 |
| 5 | Coconut Water | drinks | 5.20 | 60 |
Exact matches, AND, exclude()
Several keyword arguments in one filter() are combined with AND. Chaining filter() calls also means AND. exclude() negates its conditions:
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
class Product(models.Model):
name = models.CharField(max_length=50)
category = models.CharField(max_length=20)
price = models.DecimalField(max_digits=6, decimal_places=2)
stock = models.IntegerField()
class Meta:
app_label = "demo"
with connection.schema_editor() as editor:
editor.create_model(Product)
Product.objects.bulk_create([Product(name=n, category=c, price=p, stock=s) for n, c, p, s in [
("Green Tea", "drinks", "4.50", 120), ("Black Coffee", "drinks", "3.00", 0),
("Rice Cracker", "snacks", "2.25", 40), ("Dark Chocolate", "snacks", "6.75", 15),
("Coconut Water", "drinks", "5.20", 60)]])
def show(label, qs):
print(f"{label:<28}", list(qs.order_by("id").values_list("name", flat=True)))
show("category='drinks'", Product.objects.filter(category="drinks"))
show("drinks AND stock=0", Product.objects.filter(category="drinks", stock=0))
show("chained filters", Product.objects.filter(category="drinks").filter(stock__gt=0))
show("exclude drinks", Product.objects.exclude(category="drinks"))category='drinks' ['Green Tea', 'Black Coffee', 'Coconut Water']
drinks AND stock=0 ['Black Coffee']
chained filters ['Green Tea', 'Coconut Water']
exclude drinks ['Rice Cracker', 'Dark Chocolate']
Field lookups
| Lookup | SQL idea | Example |
|---|---|---|
exact / iexact |
= (case-insensitive with i) |
name__iexact="green tea" |
contains / icontains |
LIKE '%x%' |
name__icontains="tea" |
startswith / endswith (+ i versions) |
LIKE 'x%' |
name__startswith="Co" |
gt, gte, lt, lte |
>, >=, <, <= |
price__lt=5 |
in |
IN (...) |
id__in=[1, 3] |
range |
BETWEEN a AND b |
price__range=(3, 5) |
isnull |
IS NULL / IS NOT NULL |
email__isnull=True |
year, month, day, week_day |
date parts | published__year=2026 |
regex / iregex |
regular expression | name__regex=r"^[A-C]" |
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
class Product(models.Model):
name = models.CharField(max_length=50)
category = models.CharField(max_length=20)
price = models.DecimalField(max_digits=6, decimal_places=2)
stock = models.IntegerField()
class Meta:
app_label = "demo"
with connection.schema_editor() as editor:
editor.create_model(Product)
Product.objects.bulk_create([Product(name=n, category=c, price=p, stock=s) for n, c, p, s in [
("Green Tea", "drinks", "4.50", 120), ("Black Coffee", "drinks", "3.00", 0),
("Rice Cracker", "snacks", "2.25", 40), ("Dark Chocolate", "snacks", "6.75", 15),
("Coconut Water", "drinks", "5.20", 60)]])
def show(label, **lookups):
names = Product.objects.filter(**lookups).order_by("id").values_list("name", flat=True)
print(f"{label:<26}", list(names))
show("name__icontains='co'", name__icontains="co")
show("name__startswith='D'", name__startswith="D")
show("price__lt=4", price__lt=4)
show("price__range=(3, 5)", price__range=(3, 5))
show("stock__gte=60", stock__gte=60)
show("id__in=[1, 4, 9]", id__in=[1, 4, 9])
show("name__iexact='green tea'", name__iexact="green tea")
show("name__endswith='er'", name__endswith="er")name__icontains='co' ['Black Coffee', 'Dark Chocolate', 'Coconut Water']
name__startswith='D' ['Dark Chocolate']
price__lt=4 ['Black Coffee', 'Rice Cracker']
price__range=(3, 5) ['Green Tea', 'Black Coffee']
stock__gte=60 ['Green Tea', 'Coconut Water']
id__in=[1, 4, 9] ['Green Tea', 'Dark Chocolate']
name__iexact='green tea' ['Green Tea']
name__endswith='er' ['Rice Cracker', 'Coconut Water']
range is inclusive on both ends, so 3.00 was included.
Note: SQLite's
LIKEis case-insensitive for ASCII letters, socontainsbehaves likeicontainson SQLite. PostgreSQL and MySQL may differ — use theilookups whenever you mean case-insensitive.
Dates and NULL
Date fields support lookups on their parts, and isnull finds missing values:
import django, datetime
from django.conf import settings
settings.configure(DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}})
django.setup()
from django.db import models, connection
class Event(models.Model):
title = models.CharField(max_length=50)
day = models.DateField()
venue = models.CharField(max_length=50, null=True)
class Meta:
app_label = "demo"
with connection.schema_editor() as editor:
editor.create_model(Event)
d = datetime.date
Event.objects.bulk_create([
Event(title="Tet party", day=d(2026, 2, 17), venue="Hall A"),
Event(title="Spring meetup", day=d(2026, 3, 21)),
Event(title="Hackathon", day=d(2025, 11, 8), venue="Lab 3"),
])
print(list(Event.objects.filter(day__year=2026).order_by("day").values_list("title", flat=True)))
print(list(Event.objects.filter(day__month__gte=3).order_by("day").values_list("title", flat=True)))
print(list(Event.objects.filter(day__gt=d(2026, 1, 1), venue__isnull=False).values_list("title", flat=True)))
print(list(Event.objects.filter(venue__isnull=True).values_list("title", flat=True)))['Tet party', 'Spring meetup']
['Hackathon', 'Spring meetup']
['Tet party']
['Spring meetup']
Lookups can even be stacked: day__month__gte=3 means "the month part of day is at least 3".
Lookups are safe from SQL injection
Because values are sent as parameters, user input can't change the query. Even a hostile search string is just text:
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
class Product(models.Model):
name = models.CharField(max_length=50)
class Meta:
app_label = "demo"
with connection.schema_editor() as editor:
editor.create_model(Product)
Product.objects.create(name="Green Tea")
search = "x' OR '1'='1"
qs = Product.objects.filter(name__icontains=search)
print("matches:", qs.count())
sql, params = qs.query.sql_with_params()
print(sql)
print(params)matches: 0
SELECT "demo_product"."id", "demo_product"."name" FROM "demo_product" WHERE "demo_product"."name" LIKE %s ESCAPE '\'
("%x' OR '1'='1%",)
The %s placeholder is filled in by the database driver, never by string concatenation.
Test yourself
Which filter finds products whose name contains "tea" in any letter case?
- filter(name="tea")
- filter(name__contains="tea")
- filter(name__icontains="tea")
- filter(name__like="%tea%")
How are two keyword arguments in a single filter() call combined?
- OR
- AND
- XOR
- Only the first is used
Which lookup checks for NULL values?
- field=None only
- field__isnull=True
- field__null
- field__empty=True