Chapter 9 · 10 min read
The Django Shell and the ORM
The Django Shell and the ORM
The ORM (object-relational mapper) lets you talk to the database using Python classes and methods instead of SQL. In this chapter you will experiment with it in the Django shell and then use it in real views to show posts on web pages.
What you will learn
- How to open the Django shell.
- How to create, read, update and delete rows.
- How to filter, exclude, order and count with
QuerySets. - How to follow relations between models.
- How to display database data in views and templates.
The shell
python manage.py shell
This opens a Python prompt with Django configured. Recent Django versions import your models automatically, and the shell tells you which objects it imported. If Post is not available, import it yourself.
Managers and QuerySets
Every model has a manager called objects. Methods on the manager such as all(), filter(), exclude() and order_by() return a QuerySet, a list-like object that is lazy: no SQL runs until you loop over it, slice it, call len() or print it. You can chain methods because each returns a new QuerySet.
Practice in the shell
Type these one at a time and read the results.
from blog.models import Post
from django.contrib.auth import get_user_model
me = get_user_model().objects.first()
p = Post.objects.create(title="Hello ORM", body="Created from the shell.", author=me)
Post.objects.all()
Post.objects.count()
Post.objects.filter(published=True)
Post.objects.filter(title__icontains="orm")
Post.objects.exclude(published=True)
Post.objects.order_by("created").first()
Post.objects.get(pk=p.pk)
me.posts.all()
Post.objects.filter(author__username=me.username).values_list("title", flat=True)
print(Post.objects.filter(published=True).query)
p.title = "Renamed"
p.save()
p.delete()
What each line teaches:
| Code | Meaning |
|---|---|
Post.objects.create(...) | Make and save a row in one step |
.all() | Every row, in the model's default order |
.filter(published=True) | Rows matching the condition |
title__icontains="orm" | Lookup: case-insensitive substring match |
.exclude(...) | Rows that do not match |
.order_by("created") | Oldest first; "-created" is newest first |
.first() | The first row or None |
.get(pk=...) | Exactly one row, or an exception |
me.posts.all() | Reverse relation created by related_name="posts" |
author__username | Double underscore follows a relation |
.values_list("title", flat=True) | Only one column, as plain values |
.query | The SQL Django will run |
Common lookups
| Lookup | Example | Meaning |
|---|---|---|
exact | title="Hi" | Equal (the default) |
icontains | title__icontains="hi" | Contains, ignoring case |
startswith | title__startswith="Hi" | Begins with |
gt, gte, lt, lte | created__gte=date | Comparisons |
in | pk__in=[1, 2] | Value in a list |
isnull | author__isnull=False | Is or is not NULL |
get() versus filter()
get()returns exactly one object. It raisesPost.DoesNotExistwhen nothing matches andPost.MultipleObjectsReturnedwhen several match.filter()returns aQuerySetthat can be empty or have many rows.
In views, get_object_or_404() calls get() and turns a missing object into a 404 page.
Updating and deleting
Change an attribute and call save(). Without save() nothing is written. To change many rows at once use queryset.update(published=True), which runs one SQL statement. To delete use obj.delete() or queryset.delete().
Show data on real pages
Replace blog/views.py:
from django.shortcuts import get_object_or_404, render
from .models import Post
def post_list(request):
posts = Post.objects.filter(published=True).select_related("author")
return render(request, "blog/post_list.html", {"post_list": posts})
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
return render(request, "blog/post_detail.html", {"post": post})
Replace blog/urls.py:
from django.urls import path
from . import views
app_name = "blog"
urlpatterns = [
path("", views.post_list, name="home"),
path("post/<int:pk>/", views.post_detail, name="detail"),
]
Create blog/templates/blog/post_list.html:
{% extends "blog/base.html" %}
{% block title %}All posts{% endblock %}
{% block content %}
<h1>Latest posts</h1>
{% for post in post_list %}
<article>
<h2><a href="{{ post.get_absolute_url }}">{{ post.title }}</a></h2>
<p class="meta">by {{ post.author.username }} on {{ post.created|date:"j M Y" }}</p>
<p>{{ post.body|truncatewords:30 }}</p>
</article>
{% empty %}
<p>No posts yet.</p>
{% endfor %}
{% endblock %}
Create blog/templates/blog/post_detail.html:
{% extends "blog/base.html" %}
{% block title %}{{ post.title }}{% endblock %}
{% block content %}
<h1>{{ post.title }}</h1>
<p class="meta">by {{ post.author.username }} on {{ post.created|date:"j M Y" }}</p>
<div>{{ post.body|linebreaks }}</div>
{% endblock %}
Why the context key post_list? Later, the generic ListView supplies exactly that name, so the same template keeps working when you switch to class-based views.
The N+1 query problem
Imagine a list of 20 posts. For each post, the template reads post.author.username. Without help, Django runs one query for the posts and then one query per post for its author: 21 queries. Two tools fix this:
select_related("author")joins the author in the same query. It is the classic fix for foreign keys, used in the view above.- Fetch modes (new in Django 6.1).
Post.objects.fetch_mode(models.FETCH_PEERS)makes Django load a missing field for all instances of the sameQuerySetin one extra query, like an on-demandprefetch_related().FETCH_ONEis the default behaviour, andFETCH_RAISEraisesFieldFetchBlockedso you can catch accidental queries.
from django.db import models
for p in Post.objects.fetch_mode(models.FETCH_PEERS):
print(p.title, p.author.username)
Check it works
- The shell commands run without errors, and
Post.objects.count()matches the admin. - http://127.0.0.1:8000/ lists your published posts with links.
- Clicking a title opens
/post/1/(or the post's number) with the full text.
Exercises with solutions
Exercise 1: search
Support /?q=hello by filtering posts whose title contains the text.
Solution.
def post_list(request):
posts = Post.objects.filter(published=True).select_related("author")
q = request.GET.get("q")
if q:
posts = posts.filter(title__icontains=q)
return render(request, "blog/post_list.html", {"post_list": posts})
request.GET is a dictionary-like object of query-string values. Because QuerySets are lazy and chainable, you can add a filter conditionally.
Exercise 2: count in the shell
How many posts does each user have?
Solution.
from django.db.models import Count
from django.contrib.auth import get_user_model
get_user_model().objects.annotate(n=Count("posts")).values_list("username", "n")
annotate adds a computed value to each user, here the number of related posts.
Exercise 3: hide drafts
Do not show unpublished posts on the detail page unless the visitor is the author.
Solution.
from django.http import Http404
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
if not post.published and post.author != request.user:
raise Http404
return render(request, "blog/post_detail.html", {"post": post})
Common mistakes
- Using
get()when several rows might match. Usefilter()for lists. - Changing an attribute and forgetting
save(). - Looping over related objects in a template without
select_related. It hides dozens of queries. - Expecting a
QuerySetto run immediately. It is lazy until you use it. - Using a URL name in
{% url %}before you defined it. Django raisesNoReverseMatch. - Calling
update()and expectingsave()side effects.update()skipssave()and signals.
Key takeaways
Model.objectsis the entry point to the ORM.filter,exclude,order_byreturn lazy, chainableQuerySets.- Double underscores express lookups and relations.
- Use
select_related(or Django 6.1 fetch modes) to avoid extra queries. get_object_or_404turns a missing row into a proper 404 page.
Official links
- Making queries: https://docs.djangoproject.com/en/6.1/topics/db/queries/
- QuerySet reference: https://docs.djangoproject.com/en/6.1/ref/models/querysets/
- Database access optimization: https://docs.djangoproject.com/en/6.1/topics/db/optimization/
