Django ORM Query Cheat Sheet
The QuerySet calls I use from the Django shell to read and write data. Project commands (dbshell, migrations, data migrations) are in Django CLI Cheat Sheet.
Opening a Shell
# Python REPL with Django loaded
python manage.py shell
# The same, inside a Docker Compose service
docker compose exec <service> python manage.py shell
# Models plus common helpers (Q, F, Count, timezone…) pre-imported (needs django-extensions)
python manage.py shell_plus
Since Django 5.2, shell imports the models of every installed app by itself (--verbosity=2 lists them). On older versions, import the model first:
from apps.notes.models import Note
Reading Objects
| Call | Returns | When nothing (or several) match |
|---|---|---|
Note.objects.get(pk=1) |
one object | raises Note.DoesNotExist (or Note.MultipleObjectsReturned) |
Note.objects.all() |
QuerySet of every row | empty QuerySet |
Note.objects.filter(...) |
QuerySet of matching rows | empty QuerySet |
Note.objects.exclude(...) |
QuerySet of the other rows | empty QuerySet |
qs.first() / qs.last() |
one object (by primary key if unordered) | None |
qs.count() |
integer, via SELECT COUNT(*) |
0 |
qs.exists() |
boolean | False |
Note.objects.get(pk=1).title
# Chained calls add conditions (AND)
Note.objects.filter(text__icontains="note").exclude(title__icontains="second")
QuerySets are lazy: building and chaining them runs no SQL. The query runs when the result is iterated, printed, or passed to list(), len() or bool().
Field Lookups
A lookup follows the field name after a double underscore: field__lookup=value. With a single underscore (text_icontains) Django looks for a field of that name and raises FieldError.
| Lookup | Matches | Example |
|---|---|---|
exact (default) |
equal value | filter(pk=2) |
iexact |
equal, ignoring case | filter(title__iexact="learned today") |
contains / icontains |
substring, case-sensitive / ignoring case | filter(text__icontains="second") |
startswith / istartswith |
prefix | filter(title__startswith="title") |
in |
value in a list | filter(pk__in=[1, 3]) |
gt, gte, lt, lte |
comparisons | filter(pk__gt=1) |
isnull |
NULL or not |
filter(category__isnull=True) |
Creating Objects
# Build and save in one call
Note.objects.create(title="Third note", text="Third note's text")
# Or build, then save
note = Note(title="Draft", text="...")
note.save()
# Users: create_user() hashes the password
from django.contrib.auth import get_user_model
get_user_model().objects.create_user("developer", "developer@example.com", "a-strong-password")
Updating and Deleting
task = Task.objects.get(pk=1)
task.status = "COMPLETED"
task.save() # UPDATE of that row
Task.objects.filter(status="ARCHIVED").update(status="COMPLETED") # one UPDATE, no save(), no signals
Task.objects.filter(pk=3).delete()
To change existing data as part of a deploy, put the update() in a data migration (see the CLI cheat sheet).
Seeing the SQL
print(Task.objects.exclude(status="ARCHIVED").query)
.query shows the SQL Django builds for a QuerySet, without running it. Django fills in the parameters itself for display, so read it rather than pasting it into dbshell. With DEBUG = True, django.db.connection.queries lists the queries actually executed.
References
- Django documentation: Making queries - QuerySets, laziness, chaining and field lookups.
- Django documentation: QuerySet API reference - every method and lookup, including the SQLite case-sensitivity note.
- Django 5.2 release notes - automatic model imports in
shell(checked 2026-10-26). - Django documentation: Creating users -
create_user()and password hashing. - django-extensions: shell_plus - the auto-importing shell.
- LinkedIn Learning, Django Essential Training - the course where I first practised these shell queries.
- Django CLI Cheat Sheet -
dbshell, migrations and data migrations. - Django MOC - hub for Django notes.
Review cards
Flashcard When do you use get() rather than filter().first()?
get() when exactly one row must exist: it raises DoesNotExist or MultipleObjectsReturned. filter().first() when 'none' is a normal answer and returns None. In a view, get_object_or_404().
Flashcard How can you see the SQL query that Django builds for a QuerySet without executing it?
Use print(Task.objects.exclude(status='ARCHIVED').query) to see the SQL without running it.
Flashcard How can you update multiple rows in a QuerySet without saving each one individually?
Use Task.objects.filter(status='ARCHIVED').update(status='COMPLETED') to update multiple rows in one call.
Quiz Which lookup matches a substring regardless of case?
- startswith
- contains
- icontains
- iexact
contains is case-sensitive; the i- prefix makes a lookup case-insensitive. iexact compares the whole value.