Django
What's the difference between `get()`, `filter()`, and `all()` on a queryset?
Short Answer
filter() and all() are lazy and return a new QuerySet; get() is eager and returns a model instance. Neither filter() nor all() touches the database — each clones the underlying Query object, adjusts it, and hands back a new queryset, so a chain of them costs nothing until something iterates it. get() has no lazy form: it applies the lookups, runs the query immediately with a LIMIT 21, and either returns exactly one instance or raises DoesNotExist or MultipleObjectsReturned. The practical rule follows from that — get() when you expect exactly one row and want the absence of one to be an error, filter() when you expect a set.
How It Works
A QuerySet holds a Query object, which is a structured description of the SQL to build — the tables involved, a tree of WHERE conditions, the joins, the ordering — and no rows at all. filter() copies that Query, adds conditions to the copy, and wraps it in a new QuerySet. all() does the same with no conditions added. Because both return clones, the original is untouched, and building a ten-call chain issues zero queries.
Evaluation happens when something needs rows: iterating, list(), len(), bool(), or slicing with a step. At that point a backend-specific compiler turns the Query into SQL, runs it, and converts the rows into model instances stored on the queryset as _result_cache. Iterating the same queryset again reads that cache rather than the database, which is why a queryset is cheap to reuse but stale the moment the underlying table changes.
get() is a different kind of operation. It clones with the given lookups like filter() does, but then forces execution rather than returning the clone. Before running, it caps the query at 21 rows — MAX_GET_RESULTS — because it needs to distinguish "one row" from "more than one" and has no reason to drag back an unbounded result set to find out. Zero rows raises DoesNotExist, more than one raises MultipleObjectsReturned, and exactly one returns the instance itself, not a queryset.
all() looks redundant on a manager, where Model.objects.all() simply produces the base queryset. On an existing queryset it earns its place differently: it returns a copy with an empty _result_cache, which is the idiomatic way to force a refetch of data you have already evaluated.
One consequence of cloning is easy to miss. Because each filter() call builds its own conditions, chaining two calls across a multi-valued relation adds a separate join per call. filter(a=1, b=2) requires one related row satisfying both conditions; .filter(a=1).filter(b=2) allows two different related rows to satisfy one condition each. On ordinary fields of the model's own table the distinction cannot arise, which is why it surprises people the first time they cross a relation.
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 so the package imports, then replace main.py for each later step. Run with:
python3 main.py
Building a queryset runs nothing
The fixture, then two chained calls and a count of the queries they cost.
# depot/models.py
from django.db import models
class Shipment(models.Model):
reference = models.CharField(max_length=20)
dock = models.CharField(max_length=20)
class Scan(models.Model):
shipment = models.ForeignKey(Shipment, related_name="scans", on_delete=models.CASCADE)
dock = models.CharField(max_length=20)
flag = models.CharField(max_length=20)
# 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 Scan, Shipment
def seed():
with connection.schema_editor() as editor:
editor.create_model(Shipment)
editor.create_model(Scan)
first = Shipment.objects.create(reference="SHP-4471", dock="dock-7")
second = Shipment.objects.create(reference="SHP-4408", dock="dock-7")
Shipment.objects.create(reference="SHP-3157", dock="dock-9")
Scan.objects.create(shipment=first, dock="dock-7", flag="ok")
Scan.objects.create(shipment=first, dock="dock-9", flag="damaged")
Scan.objects.create(shipment=second, dock="dock-7", flag="damaged")
connection.queries_log.clear()
# main.py
from bootstrap import Shipment, connection, seed
seed()
pending = Shipment.objects.all()
at_dock_7 = pending.filter(dock="dock-7").order_by("reference")
print("queries after building both querysets:", len(connection.queries))
print("compiled SQL:", at_dock_7.query)
rows = list(at_dock_7)
print("queries after iterating :", len(connection.queries))
print("rows:", [shipment.reference for shipment in rows])
queries after building both querysets: 0
compiled SQL: SELECT "depot_shipment"."id", "depot_shipment"."reference", "depot_shipment"."dock" FROM "depot_shipment" WHERE "depot_shipment"."dock" = dock-7 ORDER BY "depot_shipment"."reference" ASC
queries after iterating : 1
rows: ['SHP-4408', 'SHP-4471']
all(), filter(), and order_by() together cost zero queries, and the SQL exists in full before a single row is fetched. The whole chain collapses into one statement at iteration time — the WHERE and the ORDER BY are compiled together, not applied one after another in Python. pending is still the unfiltered queryset, because filter() returned a clone rather than mutating it.
Note: str(queryset.query) interpolates parameters without quoting, so = dock-7 is a debugging view rather than runnable SQL. connection.queries shows what the driver actually received.
Try it: Add print("pending was never run:", pending._result_cache is None) at the end. at_dock_7 was built from pending and then iterated; did pending run as well? You get True. filter() did not modify pending; it returned a clone with one more condition, and the clone is what executed the query. The base queryset remains an unexecuted description that you can reuse for another filter.
get() runs immediately, and caps itself at 21 rows
Replace main.py. The same lookups as filter(), with the eager behaviour and both failure modes.
# main.py
from bootstrap import Shipment, connection, seed
seed()
shipment = Shipment.objects.get(reference="SHP-4471")
print("get() returned:", shipment.reference)
print("queries run :", len(connection.queries))
print("SQL :", connection.queries[-1]["sql"])
try:
Shipment.objects.get(reference="SHP-0000")
except Shipment.DoesNotExist as exc:
print("no match :", type(exc).__name__)
try:
Shipment.objects.get(dock="dock-7")
except Shipment.MultipleObjectsReturned as exc:
print("two matches :", exc)
get() returned: SHP-4471
queries run : 1
SQL : SELECT "depot_shipment"."id", "depot_shipment"."reference", "depot_shipment"."dock" FROM "depot_shipment" WHERE "depot_shipment"."reference" = 'SHP-4471' LIMIT 21
no match : DoesNotExist
two matches : get() returned more than one Shipment -- it returned 2!
The LIMIT 21 is the visible signature of MAX_GET_RESULTS. get() must prove there is exactly one row, which means fetching at least two when more exist — but there is no value in fetching thousands, so it stops at 21 and reports the count it saw. Both exceptions are attributes of the model class, so Shipment.DoesNotExist is a distinct type from Scan.DoesNotExist and can be caught precisely.
Try it: Add print("filter().first():", Shipment.objects.filter(reference="SHP-0000").first()). It is the same lookup that raised DoesNotExist with get(); what does it do this time? It prints None, with no exception. get() asserts that exactly one row exists and contradicts you loudly; filter().first() asserts nothing. Choose by what absence means in your code: an error or a normal case.
The result cache, and what invalidates it
Replace main.py. Iterating twice, then cloning, then forcing a refetch.
# main.py
from bootstrap import Shipment, connection, seed
seed()
at_dock_7 = Shipment.objects.filter(dock="dock-7").order_by("reference")
list(at_dock_7)
print("queries after first iteration :", len(connection.queries))
list(at_dock_7)
print("queries after second iteration:", len(connection.queries))
print("result cache populated :", at_dock_7._result_cache is not None)
narrowed = at_dock_7.filter(reference="SHP-4471")
print("the clone starts empty :", narrowed._result_cache is None)
list(narrowed)
print("queries after the clone ran :", len(connection.queries))
copy = at_dock_7.all()
print("all() returns a new object :", copy is not at_dock_7)
print("with an empty cache :", copy._result_cache is None)
queries after first iteration : 1
queries after second iteration: 1
result cache populated : True
the clone starts empty : True
queries after the clone ran : 2
all() returns a new object : True
with an empty cache : True
The second iteration costs nothing — the rows are already model instances on _result_cache. Calling filter() on an evaluated queryset does not narrow those cached rows in Python; it produces a clone with an empty cache that runs its own SQL, which is why the counter moves to 2. This is the mechanism behind a common performance surprise: filtering an already-fetched queryset re-queries rather than reusing what you have. all() on that queryset is the deliberate version of the same thing — a copy with a fresh cache, used when you want current data.
Two filter() calls are not one filter() call
Replace main.py. The same two conditions, across a reverse foreign key, expressed both ways.
# main.py
from bootstrap import Shipment, seed
seed()
single = Shipment.objects.filter(scans__dock="dock-7", scans__flag="damaged")
chained = Shipment.objects.filter(scans__dock="dock-7").filter(scans__flag="damaged")
print("one filter() call :", sorted(s.reference for s in single))
print("two filter() calls:", sorted(s.reference for s in chained))
print("joins in single :", str(single.query).count("JOIN"))
print("joins in chained :", str(chained.query).count("JOIN"))
one filter() call : ['SHP-4408']
two filter() calls: ['SHP-4408', 'SHP-4471']
joins in single : 1
joins in chained : 2
Two spellings of what looks like the same question return different shipments. SHP-4471 has two scans — one at dock-7 flagged ok, one at dock-9 flagged damaged — and no single scan is both. The one-call form joins the scan table once and requires that row to satisfy both conditions, so it excludes SHP-4471. The chained form joins twice, letting each condition find its own scan row, so it includes it. Neither is wrong; they ask different questions, and the join count in the compiled SQL is what tells them apart.
Edge Cases and Gotchas
if queryset:fetches everything. Truth-testing evaluates the queryset and fills the cache.exists()issuesSELECT 1 ... LIMIT 1instead — but if the cache is already populated, both use it and cost nothing.count()is notlen().count()issuesSELECT COUNT(*)and leaves the cache empty;len()fetches every row and builds every instance. On an already-evaluated queryset,count()reads the cache.first()imposes an ordering. On an unordered queryset it addsORDER BY id ASC LIMIT 1so the result is defined, and returnsNonerather than raising — often the better shape than catchingDoesNotExist.- A queryset defined at module level caches forever. Evaluated once at import, it keeps serving those rows for the life of the process. Build querysets inside the function that uses them.
get()accepts anythingfilter()does.get(dock__startswith="dock-")is legal; the constraint is on how many rows come back, not on the lookups used.
Summary
filter() and all() clone a Query and return a queryset without touching the database; get() compiles, runs, and returns one instance or raises. Evaluation is what costs a query, the result is cached on the queryset, and any further filter() produces a fresh clone that queries again.
filter()andall()are lazy and chainable because each returns a clone; the whole chain compiles to one statement at evaluation time.get()is eager, appliesLIMIT 21to tell one row from many, and raisesDoesNotExistorMultipleObjectsReturnedinstead of returning an empty or long result.- Iterating a queryset fills
_result_cache; iterating again is free, but callingfilter()on it returns a clone with an empty cache that issues a new query. all()on an existing queryset is the idiomatic refetch — a copy of the same query with no cached rows.- Across a multi-valued relation,
filter(a=…, b=…)constrains one related row while.filter(a=…).filter(b=…)adds a second join and constrains two, giving different results from the same conditions.