Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions create-django-index-without-downtime/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# How to Create an Index in Django Without Downtime

This folder contains the sample project for the Real Python tutorial [How to Create an Index in Django Without Downtime](https://realpython.com/create-django-index-without-downtime/).

**Note:** The code in this folder has been reformatted with Ruff and might differ slightly in code style from the files that Django generates.

## Setup

The project needs a PostgreSQL server. It has been tested with Python 3.15, Django 6.1, and PostgreSQL 16, and it requires Python 3.12 or later.

Create and activate a virtual environment, then install the pinned dependencies:

```console
$ python -m venv venv/
$ source venv/bin/activate
(venv) $ python -m pip install -r requirements.txt
```

Create a PostgreSQL database and user named `app` with the password `app`, or adjust `DATABASES` in `config/settings.py` to match your server.

## Usage

The project starts in the state right after the initial migration. `app/models.py` already declares the index on `sold_at` in `Meta.indexes`. Apply the initial migration first:

```console
(venv) $ python manage.py migrate app
```

The `stages/` folder holds the final version of the `0002` migration from each section of the tutorial:

- `0002_add_index_runsql.py`: a reversible `RunSQL` migration
- `0002_add_index_separate_database_and_state.py`: a non-atomic `SeparateDatabaseAndState` migration that creates the index concurrently
- `0002_add_index_concurrently.py`: the built-in `AddIndexConcurrently` operation

To try one of them, copy it into `app/migrations/` and apply it:

```console
(venv) $ cp stages/0002_add_index_concurrently.py app/migrations/
(venv) $ python manage.py migrate app
```

Before you try the next one, migrate back to the initial migration and delete the file:

```console
(venv) $ python manage.py migrate app 0001
(venv) $ rm app/migrations/0002_add_index_concurrently.py
```

The `RunSQL` stage creates the index without updating Django's model state, so `python manage.py makemigrations --check` still reports a missing index after you apply it. The tutorial explains why.
Empty file.
5 changes: 5 additions & 0 deletions create-django-index-without-downtime/app/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from django.apps import AppConfig


class AppConfig(AppConfig):
name = "app"
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
from django.db import migrations, models


class Migration(migrations.Migration):
initial = True

dependencies = []

operations = [
migrations.CreateModel(
name="Sale",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("sold_at", models.DateTimeField(auto_now_add=True)),
("charged_amount", models.PositiveIntegerField()),
],
),
]
Empty file.
13 changes: 13 additions & 0 deletions create-django-index-without-downtime/app/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
from django.db import models


class Sale(models.Model):
sold_at = models.DateTimeField(
auto_now_add=True,
)
charged_amount = models.PositiveIntegerField()

class Meta:
indexes = [
models.Index(fields=["sold_at"], name="app_sale_sold_at_idx"),
]
Empty file.
16 changes: 16 additions & 0 deletions create-django-index-without-downtime/config/asgi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""
ASGI config for config project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/6.1/howto/deployment/asgi/
"""

import os

from django.core.asgi import get_asgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings")

application = get_asgi_application()
134 changes: 134 additions & 0 deletions create-django-index-without-downtime/config/settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
"""
Django settings for config project.
Generated by 'django-admin startproject' using Django 6.1.4.
For more information on this file, see
https://docs.djangoproject.com/en/6.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/6.1/ref/settings/
"""

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/6.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = (
"django-insecure-&ou(f82u5skm^1@6r=zig44y%!4-any(+ri8_*e=&&1=7%vd$m"
)

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"app",
]

MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
]

ROOT_URLCONF = "config.urls"

TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
],
},
},
]

WSGI_APPLICATION = "config.wsgi.application"


# Database
# https://docs.djangoproject.com/en/6.1/ref/settings/#databases

DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql",
"NAME": "app",
"USER": "app",
"PASSWORD": "app",
"HOST": "localhost",
"PORT": "5432",
}
}


# Password validation
# https://docs.djangoproject.com/en/6.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
{
"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
},
{
"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
},
{
"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
},
{
"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
},
]


# Internationalization
# https://docs.djangoproject.com/en/6.1/topics/i18n/

LANGUAGE_CODE = "en-us"

TIME_ZONE = "UTC"

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/6.1/howto/static-files/

STATIC_URL = "static/"


# Email
# https://docs.djangoproject.com/en/6.1/topics/email/#topic-email-configuration

MAILERS = {
"default": {
"BACKEND": "django.core.mail.backends.console.EmailBackend",
},
}
23 changes: 23 additions & 0 deletions create-django-index-without-downtime/config/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
"""
URL configuration for config project.
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/6.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""

from django.contrib import admin
from django.urls import path

urlpatterns = [
path("admin/", admin.site.urls),
]
16 changes: 16 additions & 0 deletions create-django-index-without-downtime/config/wsgi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""
WSGI config for config project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/6.1/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings")

application = get_wsgi_application()
23 changes: 23 additions & 0 deletions create-django-index-without-downtime/manage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""

import os
import sys


def main():
"""Run administrative tasks."""
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings")
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)


if __name__ == "__main__":
main()
2 changes: 2 additions & 0 deletions create-django-index-without-downtime/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
django==6.1.4
psycopg[binary]==3.3.9
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
from django.contrib.postgres.operations import AddIndexConcurrently
from django.db import migrations, models


class Migration(migrations.Migration):
atomic = False

dependencies = [
("app", "0001_initial"),
]

operations = [
AddIndexConcurrently(
model_name="sale",
index=models.Index(
fields=["sold_at"], name="app_sale_sold_at_idx"
),
),
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
from django.db import migrations


class Migration(migrations.Migration):
atomic = False

dependencies = [
("app", "0001_initial"),
]

operations = [
migrations.RunSQL(
'CREATE INDEX "app_sale_sold_at_idx" ON "app_sale" ("sold_at");',
reverse_sql='DROP INDEX "app_sale_sold_at_idx";',
),
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
from django.db import migrations, models


class Migration(migrations.Migration):
atomic = False

dependencies = [
("app", "0001_initial"),
]

operations = [
migrations.SeparateDatabaseAndState(
state_operations=[
migrations.AddIndex(
model_name="sale",
index=models.Index(
fields=["sold_at"], name="app_sale_sold_at_idx"
),
),
],
database_operations=[
migrations.RunSQL(
sql="""
CREATE INDEX CONCURRENTLY "app_sale_sold_at_idx"
ON "app_sale" ("sold_at");
""",
reverse_sql="""
DROP INDEX "app_sale_sold_at_idx";
""",
),
],
),
]
Loading