Skip to content

Python: Django ORM

Runs Django migrations (introspection, django_migrations, constraints) and the ORM against the database. The code is the same against the original database and against MachSQL; only the address changes.

DB_HOST=old-postgres
DB_HOST=machsql-host

Nothing else changes: not the code, not the driver, not its version, not the SQL.

  • Python 3.15
  • Django 6.1.2
  • psycopg 3.3.6
Terminal window
python3 -m venv .venv && . .venv/bin/activate
pip install -r requirements.txt
export DB_HOST=machsql-host DB_PASSWORD=...
python manage.py migrate
python manage.py demo

Expected output: inserted todo <id>, <n> open.

The program as it is kept and tested in the Mach Database for PostgreSQL repository; highlighted lines read the connection setting.

project/settings.py
"""Minimal settings: one app, the database from the environment."""
import os
SECRET_KEY = os.environ.get("DJANGO_SECRET_KEY", "example-only-not-a-secret")
DEBUG = False
ALLOWED_HOSTS: list[str] = []
INSTALLED_APPS = ["todos"]
USE_TZ = True
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql",
"HOST": os.environ["DB_HOST"], # the only value that changes
"PORT": os.environ.get("DB_PORT", "5432"),
"NAME": os.environ.get("DB_NAME", "app"),
"USER": os.environ.get("DB_USER", "app"),
"PASSWORD": os.environ["DB_PASSWORD"],
}
}
manage.py
#!/usr/bin/env python3
"""Django's command-line utility."""
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
project/__init__.py
requirements.txt
Django==6.1.2
psycopg[binary]==3.3.6
todos/__init__.py
todos/apps.py
from django.apps import AppConfig
class TodosConfig(AppConfig):
name = "todos"
todos/management/__init__.py
todos/management/commands/__init__.py
todos/management/commands/demo.py
from django.core.management.base import BaseCommand
from todos.models import Todo
class Command(BaseCommand):
help = "Insert a todo and count the open ones."
def handle(self, *args, **options):
todo = Todo.objects.create(title="write the examples")
open_count = Todo.objects.filter(done=False).count()
self.stdout.write(f"inserted todo {todo.id}, {open_count} open")
todos/migrations/__init__.py
todos/migrations/0001_initial.py
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies: list[tuple[str, str]] = []
operations = [
migrations.CreateModel(
name="Todo",
fields=[
("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
("title", models.CharField(max_length=200)),
("done", models.BooleanField(default=False)),
],
),
]
todos/models.py
from django.db import models
class Todo(models.Model):
title = models.CharField(max_length=200)
done = models.BooleanField(default=False)