← Back to Django, page 3

django-0052 · Easy fresher

What are field lookups in Django such as __contains, __gte, __in and __isnull, and how do filter(), exclude() and order_by() combine them?

A lookup is a double-underscore suffix on a field name that selects the comparison: exact, iexact, contains, icontains, startswith, gt, gte, lt, lte, in, range, isnull, and date parts like year. filter() keeps matching rows, exclude() removes them, keyword arguments in one call are combined with AND, and order_by() sorts, with a leading minus for descending order.

Full answer

Without a suffix, name="Asha" means name__exact="Asha". Common lookups:

  • Text: name__icontains="sha" (case-insensitive substring), name__startswith="A", name__iexact="asha".
  • Numbers and dates: score__gte=60, score__lt=40, score__range=(40, 60), joined__year=2026.
  • Sets: grade__in=["A", "B"].
  • Nulls: email__isnull=True. Writing email=None also works, but isnull is clearer.
  • Related fields use the same double underscore to cross relations: student__class_room__name="10A".

Several arguments in one filter() are joined by AND. Chaining .filter(a).filter(b) is the same for single-valued fields, but differs for multi-valued relations (each filter call can match a different related row). Use Q objects for OR and NOT (see the Q objects question).

exclude(grade="A") generates NOT (grade = 'A'). Nulls matter: SQL's NOT on a NULL value is unknown, and Django adds extra conditions to keep nullable columns correct, so check the SQL with str(qs.query) when unsure.

order_by("-score", "name") sorts by score descending, then name. order_by("?") is random and slow on large tables. Slicing qs[:10] adds LIMIT and OFFSET, and negative indexes are not allowed.

Lookups are case-sensitive or not depending on the database: contains on SQLite is case-insensitive for ASCII, but on PostgreSQL it is case-sensitive, which is why icontains is the portable choice.

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


class Student(models.Model):
    name = models.CharField(max_length=40)
    score = models.IntegerField()
    grade = models.CharField(max_length=2)
    email = models.EmailField(null=True, blank=True)

    class Meta:
        app_label = "school"


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

rows = [("Asha", 91, "A", "asha@example.com"), ("Ravi", 58, "C", None), ("Kiran", 74, "B", None), ("Meera", 66, "B", "m@example.com")]
for n, s, g, e in rows:
    Student.objects.create(name=n, score=s, grade=g, email=e)

names = lambda qs: [s.name for s in qs]
print(names(Student.objects.filter(name__icontains="ra")))
print(names(Student.objects.filter(score__gte=60, grade="B")))
print(names(Student.objects.filter(grade__in=["A", "C"])))
print(names(Student.objects.filter(email__isnull=True)))
print(names(Student.objects.exclude(grade="B").order_by("-score")))
print(names(Student.objects.filter(score__range=(60, 80)).order_by("name")[:1]))
print(str(Student.objects.filter(score__gte=60).exclude(grade="C").query))

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. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): ['Ravi', 'Kiran', 'Meera'] ['Kiran', 'Meera'] ['Asha', 'Ravi'] ['Ravi', 'Kiran'] ['Asha', 'Ravi'] ['Kiran'] SELECT "school_student"."id", "school_student"."name", "school_student"."score", "school_student"."grade", "school_student"."email" FROM "school_student" WHERE ("school_student"."score" >= 60 AND NOT ("school_student"."grade" = C))

Key points

  • Suffix after double underscore picks the comparison
  • Arguments in one filter() are ANDed
  • exclude() negates; mind nullable columns
  • order_by('-field') sorts descending
  • Use icontains for portable case-insensitive search

Common mistakes

  • Chaining filter() on multi-valued relations and expecting AND on the same related row
  • Using exact lookups for user search instead of icontains
  • Using order_by('?') on large tables
  • Forgetting that contains is case-sensitive on some databases

Follow-ups

  • How does filter().filter() differ from a single filter() across a ManyToMany?
  • How do you do OR queries?
  • How would you search across several fields?

Tips

  • Give 4 lookups from memory
  • Explain AND versus OR
  • Show you can print the SQL