Thuta Learning
Python
IntermediateProgrammingBeginner

Django Models & ORM

PythonLesson 3840 min

What you'll walk away with

  • Write a model class with field types and options such as max_length, default and unique
  • Explain the different jobs of makemigrations and migrate
  • Do CRUD with objects.create, filter, get, update and delete, using field lookups such as priority__gte
  • Understand that QuerySets are lazy and only run SQL when evaluated
  • Link two models with ForeignKey, related_name and on_delete

Explain it simply

Django models in plain language

A model is a Python class that describes one database table. Each class attribute is a column and each instance of the class is one row. Write a Task model and Django can create the task table for you, and you can then add, find, change and delete tasks with Python code.

The ORM, or Object-Relational Mapper, is an interpreter that turns your Python into SQL. Writing Task.objects.filter(completed=True) produces SELECT ... WHERE completed = 1 and converts the rows that come back into Task objects. The same code works on SQLite, PostgreSQL or MySQL.

Problem → Why → Solution

The problem: hand-written SQL strings

Without models, using sqlite3 directly means writing SQL strings to create tables, insert rows and select them, then reading the returned tuples by index. Adding a column means editing every query, and pasting user input straight into a string opens the door to SQL injection.

raw_sql.py
import sqlite3

db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE task (id INTEGER PRIMARY KEY, title TEXT, done INTEGER)")
db.execute("INSERT INTO task (title, done) VALUES ('Learn Django', 0)")

search = input("title: ")                     # user types: x' OR '1'='1
rows = db.execute(f"SELECT * FROM task WHERE title = '{search}'").fetchall()
for row in rows:
    print(row[1], bool(row[2]))               # which index was 'done' again?

What models and the ORM change

A model declares the table's shape in one place, and migrations change the database to match it. Queries become Python such as Task.objects.filter(title=search), and the ORM always sends parameters separately, which blocks injection. Results are read by name, task.title, instead of row[1].

Core concept: models, migrations and QuerySets

Model classes inherit from models.Model, and each field sets a column type: CharField(max_length=100) becomes a VARCHAR, IntegerField an integer, BooleanField a true/false column and DateTimeField a timestamp. Options such as default, unique, null and blank add rules to the column. Django adds an auto-incrementing id primary key for you, so you do not declare one. An inner Meta class holds table-level settings such as the default ordering, and __str__ controls how an object is shown in the admin and the shell.

Writing a model does not change the database yet. python manage.py makemigrations compares your models with the latest migration and writes the difference as a new file such as migrations/0002_... .py. python manage.py migrate then applies any migration files that have not run yet to the actual database. Migration files are committed to git so that every teammate and server ends up with the same schema.

Task.objects is a Manager, and all(), filter(), exclude() and order_by() return QuerySets. A QuerySet is lazy: building or chaining it runs no SQL, and the query is only sent when it is evaluated by looping, calling list() or len(), or printing it. Field lookups use a double underscore: priority__gte=2, title__icontains="django", id__in=[1, 2]. get() is different: it returns a single object and raises DoesNotExist when nothing matches or MultipleObjectsReturned when more than one does.

Tables are linked with a ForeignKey: author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name="books") on Book ties every book to one author. on_delete decides what happens when that author is deleted: CASCADE deletes the books too, PROTECT refuses the deletion, and SET_NULL clears the link, which requires null=True. related_name lets you read from the other side, as in author.books.all().

ORM callRoughly the SQL
Task.objects.create(title="x")INSERT INTO ... VALUES (...)
Task.objects.filter(priority__gte=2)SELECT ... WHERE priority >= 2
qs.update(priority=5)UPDATE ... SET priority = 5 WHERE ...
qs.delete()DELETE FROM ... WHERE ...
Class is table, object is row, QuerySet is a question
  1. A model class describes a table
  2. Migrations make the database match
  3. A QuerySet builds up a question
  4. SQL runs only when it is evaluated

Every time you change a model, run makemigrations and migrate as a pair.

General pattern

python
class ModelName(models.Model):
    field_name = models.CharField(max_length=100)
    other = models.ForeignKey(Other, on_delete=models.CASCADE, related_name="items")

    class Meta:
        ordering = ["field_name"]

obj = ModelName.objects.create(field_name=value)
qs = ModelName.objects.filter(field_name__lookup=value).order_by("-other")
one = ModelName.objects.get(pk=some_id)        # DoesNotExist if missing
qs.update(field_name=new_value)
qs.delete()

Declare a class with fields and a Meta, then call create, filter, get, update and delete through its manager, objects. filter calls can be chained, while get returns exactly one object.

Worked example: Task CRUD on an in-memory database

So that it runs as one file, the program below starts with a little boilerplate: settings.configure() points Django at an in-memory SQLite database, and INSTALLED_APPS=["__main__"] says this script itself is the app. connection.schema_editor() temporarily stands in for migrate by creating the table. All of this is only for the demo; in a real project settings.py and migration files do these jobs.

The table name combines the app label and the model name, giving __main___task; for a Task model in a real app called tasks it would be tasks_task.

task_orm.py
# Single-file demo setup: in a real project this lives in settings.py
import django
from django.conf import settings

settings.configure(
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3",
                           "NAME": ":memory:"}},
    INSTALLED_APPS=["__main__"],     # this script plays the role of the app
)
django.setup()

from django.db import connection, models


class Task(models.Model):
    title = models.CharField(max_length=100)
    priority = models.IntegerField(default=1)
    completed = models.BooleanField(default=False)

    class Meta:
        ordering = ["-priority", "title"]

    def __str__(self):
        return self.title


with connection.schema_editor() as editor:   # stands in for migrate
    editor.create_model(Task)

# Create
Task.objects.create(title="Learn Django", priority=3)
Task.objects.create(title="Write tests", priority=2)
chore = Task(title="Buy milk")                # only a Python object so far
chore.save()                                  # the INSERT happens here

# Read
print(Task.objects.count(), "tasks:", list(Task.objects.all()))
urgent = Task.objects.filter(priority__gte=2)
print("urgent:", [t.title for t in urgent])
sql = str(urgent.query)                       # the SQL Django generated
print(sql[sql.index("WHERE"):])

# Update one row, then many rows with a single query
task = Task.objects.get(title="Learn Django")
task.completed = True
task.save()
changed = Task.objects.filter(priority=1).update(priority=5)
print("rows updated:", changed)
print(list(Task.objects.values_list("title", "priority", "completed")))

# Delete
deleted, _ = Task.objects.filter(completed=True).delete()
print("deleted:", deleted, "left:", Task.objects.count())

Code breakdown

  1. Declare the table title = models.CharField(max_length=100)

    CharField is a text column that requires max_length. priority is an integer with default=1 and completed a boolean with default=False. Django adds the id column automatically.

  2. Default ordering ordering = ["-priority", "title"]

    Every query sorts by priority, highest first (the minus means descending), then by title. That is why the printed SQL ends with ORDER BY ... DESC, ... ASC.

  3. Two ways to createchore.save() # the INSERT happens here

    objects.create() builds and saves in one step. Task(...) is only a Python object until save() runs the INSERT and assigns an id.

  4. Lazy QuerySet, visible SQLsql = str(urgent.query) # the SQL Django generated

    urgent is a filtered QuerySet that only runs when the list comprehension loops over it. Converting .query to a string shows the SQL Django generated, where priority__gte=2 became >= 2.

  5. Bulk updatechanged = Task.objects.filter(priority=1).update(priority=5)

    update() changes every matching row with one UPDATE statement and returns how many rows changed. It does not call the model's save() method.

  6. Delete returns countsdeleted, _ = Task.objects.filter(completed=True).delete()

    delete() returns a tuple: the total number of rows removed and a dict of counts per model. Here only Learn Django, the completed task, is removed.

You should see
3 tasks: [<Task: Learn Django>, <Task: Write tests>, <Task: Buy milk>]
urgent: ['Learn Django', 'Write tests']
WHERE "__main___task"."priority" >= 2 ORDER BY "__main___task"."priority" DESC, "__main___task"."title" ASC
rows updated: 1
[('Buy milk', 5, False), ('Learn Django', 3, True), ('Write tests', 2, False)]
deleted: 1 left: 2

Models, migrations and admin in a real project

In a real project the model lives in the app's models.py, and the app label comes from the app's folder name. The snippets below need a project with manage.py, so they are not run here.

tasks/models.py
from django.db import models


class Task(models.Model):
    title = models.CharField(max_length=100)
    completed = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title
tasks/admin.py
from django.contrib import admin

from .models import Task


@admin.register(Task)
class TaskAdmin(admin.ModelAdmin):
    list_display = ["title", "completed", "created_at"]
    list_filter = ["completed"]

Write or change the model

For example, add the new created_at field to models.py.

python manage.py makemigrations

Writes the change as a new file in tasks/migrations/. Read it, then commit it to git.

python manage.py migrate

Applies pending migrations to the database. Run it on every server as part of each deploy.

In real projects

Models and the ORM in real projects

Models sit at the centre of every Django project. Views, forms, the admin and API serializers are all built on them, so a good model design makes everything else easier. The ORM covers the vast majority of everyday queries, and teams drop to raw SQL only for unusual reports. Migrations also become the written history of how the schema evolved.

  • To-do apps: one Task model plus admin.site.register gives staff a CRUD interface without writing any views.
  • Blogs: Post and Comment are linked with ForeignKey(Post, related_name="comments"), and post.comments.all() reads a post's comments.
  • E-commerce: Product, Order and OrderItem models feed sales reports through aggregations such as annotate(Sum(...)), with select_related keeping the number of queries down.

Common mistakes

Common mistakes with models and the ORM

Changing a model without migrating

Add a field without running makemigrations and migrate, and the database lacks the column, so queries fail with 'no such column' or 'column does not exist'. Generating the migration but not committing it leaves teammates' databases out of step.

Confusing get() with filter()

filter() returns a QuerySet, so Task.objects.filter(pk=1).title is an AttributeError. get() returns an object but raises Task.DoesNotExist when nothing matches, so catch it with try/except, or use get_object_or_404 inside a view. When you want the object or None, use filter(...).first().

Querying related objects inside a loop (N+1)

for book in Book.objects.all(): print(book.author.name) sends one extra author query per book, so 100 books cost 101 queries. Book.objects.select_related("author") fetches them in a single JOIN.

Best practices

Best practices

  • Give every model a __str__ so the admin, the shell and error messages stay readable.
  • Read each migration file before committing it and look for changes that could lose data.
  • Use select_related or prefetch_related when a loop reads related objects.
  • Use update() for bulk changes and keep per-object save() for edits that need model logic.

Mini challenge

Mini challenge: Author and Book

Build Author and Book models linked by a ForeignKey on an in-memory database. After adding data, use the ORM to list one author's books, find authors who published after 1900, and compute each author's book count and average page count. Finally delete an author to show what CASCADE does.

  • Book.author is ForeignKey(Author, on_delete=models.CASCADE, related_name="books")
  • Print book titles through the reverse relation, such as austen.books.all()
  • Filter across the relation with books__year__gte and use distinct()
  • Summarise per author with annotate(Count, Avg), then show how many books remain after deleting an author
library.py
import django
from django.conf import settings

# TODO: settings.configure(...) with an in-memory SQLite database
#       and INSTALLED_APPS=["__main__"], then django.setup()

from django.db import connection, models
from django.db.models import Avg, Count


class Author(models.Model):
    # TODO: a unique name field and __str__
    ...


class Book(models.Model):
    # TODO: title, year, pages and a ForeignKey to Author
    #       (on_delete=CASCADE, related_name="books"); order by year
    ...


# TODO: create both tables with connection.schema_editor()
# TODO: add 2 authors and 3 books
# TODO: print one author's books, modern authors, and per-author stats
# TODO: delete an author and print how many books are left

Expected: Austen: ['Emma', 'Persuasion'], modern authors: ['Frank Herbert'], Frank Herbert: 1 books, 412.0 pages, Jane Austen: 2 books, 361.5 pages, and books left: 2 after deleting Herbert.

Show hint

Use the related_name inside queries: Author.objects.filter(books__year__gte=1900). The join can return an author once per matching book, hence distinct(). annotate(n=Count("books"), avg=Avg("books__pages")) adds n and avg attributes to every author.

Show solution
library.py
import django
from django.conf import settings

settings.configure(
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3",
                           "NAME": ":memory:"}},
    INSTALLED_APPS=["__main__"],
)
django.setup()

from django.db import connection, models
from django.db.models import Avg, Count


class Author(models.Model):
    name = models.CharField(max_length=80, unique=True)

    def __str__(self):
        return self.name


class Book(models.Model):
    title = models.CharField(max_length=120)
    year = models.IntegerField()
    pages = models.PositiveIntegerField()
    author = models.ForeignKey(Author, on_delete=models.CASCADE,
                               related_name="books")

    class Meta:
        ordering = ["year"]


with connection.schema_editor() as editor:
    editor.create_model(Author)
    editor.create_model(Book)

austen = Author.objects.create(name="Jane Austen")
herbert = Author.objects.create(name="Frank Herbert")
Book.objects.create(title="Emma", year=1815, pages=474, author=austen)
Book.objects.create(title="Persuasion", year=1817, pages=249, author=austen)
Book.objects.create(title="Dune", year=1965, pages=412, author=herbert)

print("Austen:", [b.title for b in austen.books.all()])
modern = Author.objects.filter(books__year__gte=1900).distinct()
print("modern authors:", [a.name for a in modern])
stats = Author.objects.annotate(n=Count("books"), avg=Avg("books__pages"))
for a in stats.order_by("name"):
    print(f"{a.name}: {a.n} books, {a.avg:.1f} pages on average")
herbert.delete()                         # CASCADE removes his books too
print("books left:", Book.objects.count())

Quick quiz 1 / 3

How many database queries does the single line qs = Task.objects.filter(completed=False) send?

Quick quiz 2 / 3

If no row has title="Nope", what does Task.objects.get(title="Nope") do?

Quick quiz 3 / 3

You add a new due_date field to the Task model. What must you run so the database matches?

What to remember

  • A model class is a table, a field is a column and an object is a row; Django adds the id primary key.
  • makemigrations records changes as files and migrate applies them to the database.
  • QuerySets are lazy, lookups use double underscores, and get() returns exactly one object.
  • ForeignKey with related_name lets you query from both sides, and on_delete decides what happens on deletion.

Django — Getting Started — Django Software Foundation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Django Models & ORM | Thuta Learning