← Back to Django, page 1

django-0005 · Easy fresher

What is a QuerySet in Django, and what does it mean that QuerySets are lazy?

A QuerySet is a collection of rows described by a query, built with methods like filter(), exclude() and order_by(). It is lazy: building or chaining it runs no SQL. The query runs only when the results are needed, for example when you loop over it, slice with a step, call list(), len() or bool(), or print it.

Full answer

Student.objects is a Manager. Calling methods such as .all(), .filter(marks__gte=40), .exclude(...) or .order_by("-marks") on it returns a QuerySet. Each call returns a new QuerySet, so you can chain them.

Lazy means Django only builds a description of the SQL until it really needs data. These actions run the query (Django calls this "evaluating" the QuerySet):

  • iterating: for s in qs:
  • list(qs), len(qs), bool(qs) or if qs:
  • repr(qs) (what the shell shows)
  • slicing with a step, such as qs[::2]

Once evaluated, a QuerySet caches its rows. Looping over the same QuerySet twice uses the cache. But creating a new QuerySet (for example qs.filter(...) again) runs a new query.

Methods that run immediately and return something other than a QuerySet: get(), first(), count(), exists(), aggregate(), create(), update(), delete().

get() returns exactly one object. It raises DoesNotExist when there is none and MultipleObjectsReturned when there are several. first() returns None when empty.

Field lookups use a double underscore: name__icontains="an", marks__range=(40, 60), class_room__name="10A" (follows a relation).

Practical tip: use exists() to check if any row matches and count() for a number, instead of loading full objects with len(), unless you need the objects anyway.

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
from django.test.utils import CaptureQueriesContext


class Student(models.Model):
    name = models.CharField(max_length=50)
    marks = models.IntegerField()

    class Meta:
        app_label = "school"


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

Student.objects.bulk_create([
    Student(name="Asha", marks=91), Student(name="Ravi", marks=38), Student(name="Kiran", marks=67),
])

with CaptureQueriesContext(connection) as ctx:
    passed = Student.objects.filter(marks__gte=40).order_by("-marks")  # no SQL yet
    print("queries after building:", len(ctx.captured_queries))
    names = [s.name for s in passed]                                     # runs SQL
    again = [s.name for s in passed]                                     # uses the cache
    print("queries after two loops:", len(ctx.captured_queries))

print(names, again == names)
print(Student.objects.filter(marks__lt=40).exists(), Student.objects.count())

try:
    Student.objects.get(marks__gte=40)
except Student.MultipleObjectsReturned:
    print("get() found more than one row")

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): queries after building: 0 queries after two loops: 1 ['Asha', 'Kiran'] True True 3 get() found more than one row

Key points

  • QuerySets are built lazily and run on evaluation
  • Chaining returns new QuerySets
  • Evaluated QuerySets cache their results
  • get() raises DoesNotExist or MultipleObjectsReturned
  • Prefer exists() and count() when you do not need objects

Common mistakes

  • Thinking every chained call hits the database
  • Calling len(qs) only to get a count
  • Expecting a re-filtered QuerySet to reuse the earlier cache
  • Using get() where zero or many rows are possible without handling the exceptions

Follow-ups

  • What is the difference between qs.count() and len(qs)?
  • When does slicing a QuerySet run a query?
  • How would you see the SQL a QuerySet will run?

Tips

  • List three things that evaluate a QuerySet
  • Mention the result cache and when it is not reused
  • Show you know print(qs.query) for inspecting SQL