Skip to content
Kuza Ndoto Academy

ORM Queries

IntermediateChapter 4 · Page 14 of 235 min readUpdated 15 Nov 2026

Django's ORM (Object-Relational Mapper) lets you create, read, update and delete database records using Python methods instead of SQL. This page uses the Event model from the Migrations page to cover the queries you'll use every day.

The Django shell

The best place to practise queries is the Django shell, a Python prompt with your project loaded:

python manage.py shell

Django 5.2 imports your models automatically when the shell starts, but the examples below import things explicitly so they also work in your own code. They assume the events table starts empty.

Create

Every model has a manager called objects. Use create() to build and save a record in one step:

>>> from datetime import datetime
>>> from zoneinfo import ZoneInfo
>>> from events.models import Event
>>> EAT = ZoneInfo("Africa/Nairobi")
>>> Event.objects.create(
...     title="Freshers' Welcome Night",
...     venue="Main Hall",
...     starts_at=datetime(2026, 11, 20, 18, 0, tzinfo=EAT),
...     capacity=300,
... )
<Event: Freshers' Welcome Night>

Or create an instance first and call save(). The object has no primary key until it's saved:

>>> hack = Event(title="Campus Hackathon", venue="ICT Lab 2",
...              starts_at=datetime(2026, 11, 28, 9, 0, tzinfo=EAT),
...              capacity=60, is_free=False)
>>> print(hack.pk)
None
>>> hack.save()
>>> hack.pk
2
>>> Event.objects.create(title="Career Fair", venue="Main Hall",
...                      starts_at=datetime(2026, 12, 2, 10, 0, tzinfo=EAT),
...                      capacity=500)
<Event: Career Fair>
Warning

With USE_TZ = True, always give DateTimeField a time-zone-aware value, as above, or use django.utils.timezone.now(). A "naive" datetime without tzinfo triggers a RuntimeWarning and may be stored at the wrong hour.

Read

Most read methods return a QuerySet: a list-like collection of objects. Results follow the model's Meta.ordering (by starts_at) unless you say otherwise.

>>> Event.objects.all()
<QuerySet [<Event: Freshers' Welcome Night>, <Event: Campus Hackathon>, <Event: Career Fair>]>
>>> Event.objects.count()
3
>>> Event.objects.filter(venue="Main Hall")
<QuerySet [<Event: Freshers' Welcome Night>, <Event: Career Fair>]>
>>> Event.objects.exclude(is_free=True)
<QuerySet [<Event: Campus Hackathon>]>
>>> Event.objects.order_by("-capacity")
<QuerySet [<Event: Career Fair>, <Event: Freshers' Welcome Night>, <Event: Campus Hackathon>]>
>>> Event.objects.first()
<Event: Freshers' Welcome Night>

To fetch exactly one object, use get(). It raises an exception if there are no matches or more than one:

>>> Event.objects.get(pk=2)
<Event: Campus Hackathon>
>>> Event.objects.get(pk=99)
Traceback (most recent call last):
  ...
events.models.Event.DoesNotExist: Event matching query does not exist.

In views, use get_object_or_404(Event, pk=pk), which turns that exception into a friendly 404 page.

Field lookups

Add a double underscore and a lookup name to a field to filter by more than exact equality:

LookupMeaningExample
__icontainsContains text, ignoring casetitle__icontains="night"
__startswithBegins withtitle__startswith="Career"
__gt, __gte, __lt, __lteGreater / less than (or equal)capacity__gte=100
__inIn a listvenue__in=["Main Hall", "ICT Lab 2"]
__year, __month, __dateParts of a datestarts_at__month=12
__isnullIs (or isn't) emptydescription__isnull=False
>>> Event.objects.filter(title__icontains="night")
<QuerySet [<Event: Freshers' Welcome Night>]>
>>> Event.objects.filter(capacity__gte=100)
<QuerySet [<Event: Freshers' Welcome Night>, <Event: Career Fair>]>
>>> Event.objects.filter(starts_at__month=12)
<QuerySet [<Event: Career Fair>]>

Filters can be chained, and several arguments in one filter() are combined with AND. For OR, use Q objects joined with |:

>>> from django.db.models import Q
>>> Event.objects.filter(is_free=True).exclude(venue="ICT Lab 2")
<QuerySet [<Event: Freshers' Welcome Night>, <Event: Career Fair>]>
>>> Event.objects.filter(Q(capacity__lt=100) | Q(title__icontains="fair"))
<QuerySet [<Event: Campus Hackathon>, <Event: Career Fair>]>

Update

Change one object by setting attributes and saving, or update many rows at once with update(), which returns the number of rows changed:

>>> hack = Event.objects.get(pk=2)
>>> hack.capacity = 80
>>> hack.save()
>>> Event.objects.filter(venue="Main Hall").update(venue="Great Hall")
2
>>> from django.db.models import F
>>> Event.objects.filter(pk=2).update(capacity=F("capacity") + 20)
1
>>> hack.refresh_from_db()
>>> hack.capacity
100

F("capacity") refers to the value already in the database, so the addition happens inside the database. This avoids errors when two people update the same row at the same moment.

Aggregate

>>> from django.db.models import Avg, Sum
>>> Event.objects.aggregate(Sum("capacity"))
{'capacity__sum': 900}
>>> Event.objects.aggregate(average=Avg("capacity"))
{'average': 300.0}

The total is 300 + 100 + 500 = 900 seats, and the average is 900 / 3 = 300.0.

Delete

>>> Event.objects.get(title="Career Fair").delete()
(1, {'events.Event': 1})
>>> Event.objects.count()
2

delete() returns the total number of objects deleted and a count per model. You can also delete a whole QuerySet: Event.objects.filter(is_free=False).delete().

Common mistake

Running Event.objects.all().delete() or update() on an unfiltered QuerySet "just to test". Both act on every row immediately, with no confirmation and no undo. Check your filter with .count() first.

QuerySets are lazy

Building a QuerySet doesn't touch the database. Django only runs the SQL when you actually need the results: when you loop over it, print it, call len() or list(), or test it in an if. This lets you build queries step by step at no cost:

events = Event.objects.filter(is_free=True)     # no query yet
events = events.order_by("-starts_at")         # still no query
latest_three = events[:3]                       # adds LIMIT 3, still no query
for event in latest_three:                      # the query runs here
    print(event.title)
QuerySet Event.objects .filter(is_free=True) SQL SELECT ... FROM events_event WHERE is_free Database returns rows rows come back as Event objects
Figure 1. Django writes the SQL for you, but only when the results are actually needed, such as in the for loop above.

Use exists() rather than count() > 0 when you only need to know whether anything matches; it's faster.

Key points

  • Create with objects.create() or save(); read with all(), filter(), exclude() and get().
  • Use lookups like __icontains and __gte, and Q objects for OR conditions.
  • Update with save() or update(); use F() to update from the current value.
  • delete() is permanent; filter carefully first.
  • QuerySets are lazy and only hit the database when results are needed.
Up next · Models & DatabasesThe Admin SiteA free dashboard for your data.
→

Tip: use the ← and → keys to move between pages.