Assimilating Django ORM#
← Assimilation hub · Live test fixture: frameworks/04_django/
Django PostgreSQL databases have four distinct traits that pgdorm handles cleanly out of the box:
- Framework system tables — including one ending in
_type! Every Django project hasdjango_migrationsanddjango_content_type. Because_typeis reserved forpg.TypeTableinpgdorm, passing--ignore-table django_migrations --ignore-table django_content_typeisolates Django's internal tables completely untouched (alongsideauth_*/django_admin_logif you're migrating one app at a time). <app>_<model>singular table names: Django names modelsbilling_account,billing_order,billing_tag(singular!), while its auto-generated many-to-many table is plural (billing_order_tags) and already carries its ownidsurrogate primary key plusUNIQUE (order_id, tag_id).- Modern
IDENTITYPKs & auto-indexed FKs: Modern Django migrations useGENERATED BY DEFAULT AS IDENTITYand automatically create B-tree indexes on everyForeignKey, so far fewer post-commit index builds are needed! - Optional app-prefix cleanup: By default,
pgdorm scaffoldkeepsbilling_account→BillingAccount(minimal renames). If you want to retire the Djangobilling_prefix completely, either pass a customAdoptionMap(e.g.target="account",columns={"id": "account_id"}) directly topgm.scaffold_from_db(..., adoption=...), or update bothADOPTION_MAPand the matching model classes/columns inapp/models.pybefore runningadopt-plansovalidate_adoption_map()sees exact 1-to-1 targets.
1. Before & After — Table-by-Table Schema Comparison#
Run pgdorm scaffold while ignoring Django's internal tables (including django_content_type):
pgdorm --dsn "$DATABASE_URL" \
--ignore-table django_migrations \
--ignore-table django_content_type \
scaffold --type-table billing_orderstatus --out app/models.py
Every original Django model (plus the implicit billing_order_tags M2M table) lines up directly beside its scaffolded pgdorm class below:
class Order(models.Model):
account = models.ForeignKey(Account, on_delete=models.CASCADE)
status = models.ForeignKey(OrderStatus, on_delete=models.PROTECT)
total_eur = models.DecimalField(max_digits=10, decimal_places=2, db_default=0)
placed_at = models.DateTimeField(auto_now_add=True)
tags = models.ManyToManyField(Tag, related_name="orders")
class Meta:
app_label = "billing"
class BillingOrder(pg.Table):
billing_order_id: pg.Col[int] = pg.pk(default=pg.identity())
account_id: pg.Col[int] = pg.fk(BillingAccount, on_delete=pg.enums.OnDelete.CASCADE)
status_id: pg.Col[pg.Int4] = pg.fk(BillingOrderstatusType)
total_eur: pg.Col[Decimal] = pg.col(precision=10, scale=2, default=Decimal('0.00'))
placed_at: pg.Col[datetime] = pg.col(default=pg.now())
CREATE TABLE billing_order_tags (
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
order_id BIGINT NOT NULL REFERENCES billing_order(id) ON DELETE CASCADE,
tag_id BIGINT NOT NULL REFERENCES billing_tag(id) ON DELETE CASCADE,
UNIQUE (order_id, tag_id)
);
CREATE INDEX billing_order_tags_order_id_idx ON billing_order_tags (order_id);
CREATE INDEX billing_order_tags_tag_id_idx ON billing_order_tags (tag_id);
class BillingOrderTag(pg.Table):
billing_order_tag_id: pg.Col[int] = pg.pk(default=pg.identity())
order_id: pg.Col[int] = pg.fk(BillingOrder, on_delete=pg.enums.OnDelete.CASCADE)
tag_id: pg.Col[int] = pg.fk(BillingTag, on_delete=pg.enums.OnDelete.CASCADE)
@classmethod
def __constraints__(cls) -> tuple[pg.TableConstraint, ...]:
return (
pg.Unique(cls.order_id, cls.tag_id),
pg.Index(cls.order_id),
)
CREATE TABLE django_content_type (
id INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
app_label VARCHAR(100) NOT NULL,
model VARCHAR(100) NOT NULL,
UNIQUE (app_label, model)
);
CREATE TABLE django_migrations (
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
app VARCHAR(255) NOT NULL,
name VARCHAR(255) NOT NULL,
applied TIMESTAMPTZ NOT NULL DEFAULT now()
);
Left completely untouched via ignore_tables (django_content_type, django_migrations). Never audited, renamed, or dropped by pgdorm.migrate — even when a legacy table name ends in _type.
from datetime import datetime
from decimal import Decimal
from enum import IntEnum
import pgdorm as pg
import pgdorm.migrate as pgm
class BillingOrderstatusKind(IntEnum):
PENDING = 1
PAID = 2
CANCELLED = 3
class BillingOrderstatusType(pg.TypeTable, enum=BillingOrderstatusKind):
billing_orderstatus_type_id: pg.Col[BillingOrderstatusKind] = pg.pk()
class BillingAccount(pg.Table):
billing_account_id: pg.Col[int] = pg.pk(default=pg.identity())
email: pg.Col[str] = pg.col(max_len=254, unique=True)
is_active: pg.Col[bool] = pg.col(default=True)
created_at: pg.Col[datetime] = pg.col(default=pg.now())
class BillingOrder(pg.Table):
billing_order_id: pg.Col[int] = pg.pk(default=pg.identity())
account_id: pg.Col[int] = pg.fk(BillingAccount, on_delete=pg.enums.OnDelete.CASCADE)
status_id: pg.Col[pg.Int4] = pg.fk(BillingOrderstatusType)
total_eur: pg.Col[Decimal] = pg.col(precision=10, scale=2, default=Decimal('0.00'))
placed_at: pg.Col[datetime] = pg.col(default=pg.now())
class BillingTag(pg.Table):
billing_tag_id: pg.Col[int] = pg.pk(default=pg.identity())
name: pg.Col[str] = pg.col(max_len=64, unique=True)
class BillingOrderTag(pg.Table):
billing_order_tag_id: pg.Col[int] = pg.pk(default=pg.identity())
order_id: pg.Col[int] = pg.fk(BillingOrder, on_delete=pg.enums.OnDelete.CASCADE)
tag_id: pg.Col[int] = pg.fk(BillingTag, on_delete=pg.enums.OnDelete.CASCADE)
@classmethod
def __constraints__(cls) -> tuple[pg.TableConstraint, ...]:
return (
pg.Unique(cls.order_id, cls.tag_id),
pg.Index(cls.order_id),
)
ADOPTION_MAP = pgm.AdoptionMap(
tables={
'billing_account': pgm.TableMapping(target='billing_account', columns={'id': 'billing_account_id'}, pk_strategy=pgm.enums.PkStrategy.RENAME),
'billing_order': pgm.TableMapping(target='billing_order', columns={'id': 'billing_order_id'}, pk_strategy=pgm.enums.PkStrategy.RENAME),
'billing_order_tags': pgm.TableMapping(target='billing_order_tag', columns={'id': 'billing_order_tag_id'}, pk_strategy=pgm.enums.PkStrategy.RENAME),
'billing_orderstatus': pgm.TableMapping(target='billing_orderstatus_type', columns={'id': 'billing_orderstatus_type_id'}, as_type_table=True, pk_strategy=pgm.enums.PkStrategy.RENAME),
'billing_tag': pgm.TableMapping(target='billing_tag', columns={'id': 'billing_tag_id'}, pk_strategy=pgm.enums.PkStrategy.RENAME),
},
ignore_tables=frozenset({'django_content_type', 'django_migrations'}),
)
APP = pgm.MigrationApp(tables=(BillingOrderstatusType, BillingAccount, BillingOrder, BillingTag, BillingOrderTag), ignore_tables=frozenset({'django_content_type', 'django_migrations'}))
from django.db import models
class OrderStatus(models.Model):
code = models.CharField(max_length=32, unique=True)
class Meta:
app_label = "billing"
class Account(models.Model):
email = models.EmailField(max_length=254, unique=True)
is_active = models.BooleanField(default=True, db_default=True)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
app_label = "billing"
class Tag(models.Model):
name = models.CharField(max_length=64, unique=True)
class Meta:
app_label = "billing"
class Order(models.Model):
account = models.ForeignKey(Account, on_delete=models.CASCADE)
status = models.ForeignKey(OrderStatus, on_delete=models.PROTECT)
total_eur = models.DecimalField(max_digits=10, decimal_places=2, db_default=0)
placed_at = models.DateTimeField(auto_now_add=True)
tags = models.ManyToManyField(Tag, related_name="orders")
class Meta:
app_label = "billing"
CREATE TABLE django_migrations (
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
app VARCHAR(255) NOT NULL,
name VARCHAR(255) NOT NULL,
applied TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE django_content_type (
id INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
app_label VARCHAR(100) NOT NULL,
model VARCHAR(100) NOT NULL,
UNIQUE (app_label, model)
);
CREATE TABLE billing_orderstatus (
id INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
code VARCHAR(32) NOT NULL UNIQUE
);
CREATE TABLE billing_account (
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
email VARCHAR(254) NOT NULL UNIQUE,
is_active BOOLEAN NOT NULL DEFAULT true,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE billing_tag (
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
name VARCHAR(64) NOT NULL UNIQUE
);
CREATE TABLE billing_order (
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
account_id BIGINT NOT NULL REFERENCES billing_account(id) ON DELETE CASCADE,
status_id INTEGER NOT NULL REFERENCES billing_orderstatus(id),
total_eur NUMERIC(10, 2) NOT NULL DEFAULT 0.00,
placed_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX billing_order_account_id_idx ON billing_order (account_id);
CREATE INDEX billing_order_status_id_idx ON billing_order (status_id);
CREATE TABLE billing_order_tags (
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
order_id BIGINT NOT NULL REFERENCES billing_order(id) ON DELETE CASCADE,
tag_id BIGINT NOT NULL REFERENCES billing_tag(id) ON DELETE CASCADE,
UNIQUE (order_id, tag_id)
);
CREATE INDEX billing_order_tags_order_id_idx ON billing_order_tags (order_id);
CREATE INDEX billing_order_tags_tag_id_idx ON billing_order_tags (tag_id);
INSERT INTO django_migrations (app, name) VALUES ('billing', '0001_initial');
INSERT INTO django_content_type (app_label, model) VALUES ('billing', 'order');
INSERT INTO billing_orderstatus (id, code) VALUES (1, 'pending'), (2, 'paid'), (3, 'cancelled');
INSERT INTO billing_account (email) VALUES ('[email protected]');
INSERT INTO billing_tag (name) VALUES ('enterprise');
INSERT INTO billing_order (account_id, status_id, total_eur) VALUES (1, 2, 499.00);
INSERT INTO billing_order_tags (order_id, tag_id) VALUES (1, 1);
2. Live catalog audit#
With --ignore-table django_migrations --ignore-table django_content_type, notice how quiet the audit is compared to SQLAlchemy/SQLModel: Django's FK indexes and IDENTITY columns already pass pgdorm's checks!
- Table 'billing_order_tags' appears plural; assimilate to singular snake_case.
- Table 'billing_account' PK is 'id' instead of 'billing_account_id'.
- Table 'billing_order' PK is 'id' instead of 'billing_order_id'.
- Table 'billing_order_tags' PK is 'id' instead of 'billing_order_tags_id'.
- Table 'billing_orderstatus' PK is 'id' instead of 'billing_orderstatus_id'.
- Table 'billing_tag' PK is 'id' instead of 'billing_tag_id'.
- Table 'billing_account' looks like a lookup table (Single bigint PK + unique character varying(254)
email, referenced by billing_order.) - Table 'billing_orderstatus' looks like a lookup table (Single integer PK + unique character varying(32)
code, referenced by billing_order.) - Table 'billing_tag' looks like a lookup table (Single bigint PK + unique character varying(64)
name, referenced by billing_order_tags.)
Inspect raw machine-readable audit JSON (tests/integration/migrations/onboarding/frameworks/04_django/captured/audit.json)
{
"counts": {
"blocker": 0,
"info": 3,
"migration_required": 6,
"unmanaged": 0
},
"findings": [
{
"auto_fixable": true,
"category": "naming",
"code": "TABLE_NAME_PLURAL",
"doc_anchor": "table-naming",
"message": "Table 'billing_order_tags' appears plural; assimilate to singular snake_case.",
"object_kind": "table",
"object_name": "billing_order_tags",
"severity": "migration_required",
"suggestion": "Rename table to singular snake_case via AdoptionMap.",
"table": "billing_order_tags"
},
{
"auto_fixable": true,
"category": "primary_key",
"code": "PK_NAME_MISMATCH",
"doc_anchor": "primary-keys-and-serials",
"message": "Table 'billing_account' PK is 'id' instead of 'billing_account_id'.",
"object_kind": "primary_key",
"object_name": "id",
"severity": "migration_required",
"suggestion": "Rename single int/UUID PK to `<table_name>_id`, or add surrogate PK.",
"table": "billing_account"
},
{
"auto_fixable": true,
"category": "primary_key",
"code": "PK_NAME_MISMATCH",
"doc_anchor": "primary-keys-and-serials",
"message": "Table 'billing_order' PK is 'id' instead of 'billing_order_id'.",
"object_kind": "primary_key",
"object_name": "id",
"severity": "migration_required",
"suggestion": "Rename single int/UUID PK to `<table_name>_id`, or add surrogate PK.",
"table": "billing_order"
},
{
"auto_fixable": true,
"category": "primary_key",
"code": "PK_NAME_MISMATCH",
"doc_anchor": "primary-keys-and-serials",
"message": "Table 'billing_order_tags' PK is 'id' instead of 'billing_order_tags_id'.",
"object_kind": "primary_key",
"object_name": "id",
"severity": "migration_required",
"suggestion": "Rename single int/UUID PK to `<table_name>_id`, or add surrogate PK.",
"table": "billing_order_tags"
},
{
"auto_fixable": true,
"category": "primary_key",
"code": "PK_NAME_MISMATCH",
"doc_anchor": "primary-keys-and-serials",
"message": "Table 'billing_orderstatus' PK is 'id' instead of 'billing_orderstatus_id'.",
"object_kind": "primary_key",
"object_name": "id",
"severity": "migration_required",
"suggestion": "Rename single int/UUID PK to `<table_name>_id`, or add surrogate PK.",
"table": "billing_orderstatus"
},
{
"auto_fixable": true,
"category": "primary_key",
"code": "PK_NAME_MISMATCH",
"doc_anchor": "primary-keys-and-serials",
"message": "Table 'billing_tag' PK is 'id' instead of 'billing_tag_id'.",
"object_kind": "primary_key",
"object_name": "id",
"severity": "migration_required",
"suggestion": "Rename single int/UUID PK to `<table_name>_id`, or add surrogate PK.",
"table": "billing_tag"
},
{
"auto_fixable": true,
"category": "type_table",
"code": "TYPE_TABLE_CANDIDATE",
"doc_anchor": "type-table-namespace",
"message": "Table 'billing_account' looks like a lookup table (Single bigint PK + unique character varying(254) `email`, referenced by billing_order.)",
"object_kind": "table",
"object_name": "billing_account",
"severity": "info",
"suggestion": "Review candidate; pass `--type-table <table>` or `as_type_table=True` to promote.",
"table": "billing_account"
},
{
"auto_fixable": true,
"category": "type_table",
"code": "TYPE_TABLE_CANDIDATE",
"doc_anchor": "type-table-namespace",
"message": "Table 'billing_orderstatus' looks like a lookup table (Single integer PK + unique character varying(32) `code`, referenced by billing_order.)",
"object_kind": "table",
"object_name": "billing_orderstatus",
"severity": "info",
"suggestion": "Review candidate; pass `--type-table <table>` or `as_type_table=True` to promote.",
"table": "billing_orderstatus"
},
{
"auto_fixable": true,
"category": "type_table",
"code": "TYPE_TABLE_CANDIDATE",
"doc_anchor": "type-table-namespace",
"message": "Table 'billing_tag' looks like a lookup table (Single bigint PK + unique character varying(64) `name`, referenced by billing_order_tags.)",
"object_kind": "table",
"object_name": "billing_tag",
"severity": "info",
"suggestion": "Review candidate; pass `--type-table <table>` or `as_type_table=True` to promote.",
"table": "billing_tag"
}
],
"ignored_tables": [
"django_content_type",
"django_migrations"
],
"migratable": true,
"schema": "public",
"table_count": 5,
"type_table_candidates": [
{
"code_column": "email",
"code_pg_type": "character varying(254)",
"confidence": "medium",
"pk_column": "id",
"pk_pg_type": "bigint",
"reason": "Single bigint PK + unique character varying(254) `email`, referenced by billing_order.",
"referencing_tables": [
"billing_order"
],
"table": "billing_account"
},
{
"code_column": "code",
"code_pg_type": "character varying(32)",
"confidence": "high",
"pk_column": "id",
"pk_pg_type": "integer",
"reason": "Single integer PK + unique character varying(32) `code`, referenced by billing_order.",
"referencing_tables": [
"billing_order"
],
"table": "billing_orderstatus"
},
{
"code_column": "name",
"code_pg_type": "character varying(64)",
"confidence": "high",
"pk_column": "id",
"pk_pg_type": "bigint",
"reason": "Single bigint PK + unique character varying(64) `name`, referenced by billing_order_tags.",
"referencing_tables": [
"billing_order_tags"
],
"table": "billing_tag"
}
],
"unmanaged_objects": {
"extensions": [],
"indexes": [],
"rls_policies": [],
"routines": [],
"triggers": [],
"views": []
},
"workflow_steps": [
{
"detail": "Run `pgdorm scaffold` and `pgdorm adopt-plan` (use `execute_plan_tx` inside a psycopg3 transaction when recreating views/functions atomically).",
"order": 1,
"phase": "ddl",
"summary": "Scaffold models, review AdoptionMap, and execute transactional DDL"
},
{
"detail": "Run `finalize_external()` or `pgdorm upgrade`, then verify `pgdorm drift`.",
"order": 2,
"phase": "post_commit",
"summary": "Run CONCURRENTLY indexes, VALIDATE constraints, and record ledger"
}
]
}
3. Compiled assimilation SQL#
Look how clean the resulting assimilation plan is: zero table rewrites, zero redundant FK index builds, and both django_migrations and django_content_type remain completely untouched in PostgreSQL.
-- pgdorm Assimilation Plan: 0001_assimilate (04_django)
-- Checksum: df6ce4996a8ae86c239dd4ab7ac5dddaf16d8511a62e24788a54ddd46439f3f3
-- Ignored tables: django_content_type, django_migrations
-- Preserved unmanaged objects: 0
-- ===========================================================================
-- PHASE 2 (TRANSACTIONAL DDL): Atomic pgdorm compiled schema assimilation
-- ===========================================================================
BEGIN;
-- (Optional PRE-DDL hook: DROP blocking views/matviews here)
-- [1] (ACCESS EXCLUSIVE) Rename table billing_order_tags -> billing_order_tag
ALTER TABLE "public"."billing_order_tags" RENAME TO "billing_order_tag";
-- [2] (ACCESS EXCLUSIVE) Rename table billing_orderstatus -> billing_orderstatus_type
ALTER TABLE "public"."billing_orderstatus" RENAME TO "billing_orderstatus_type";
-- [3] (ACCESS EXCLUSIVE) Rename column billing_account.id -> billing_account_id
ALTER TABLE "public"."billing_account" RENAME COLUMN "id" TO "billing_account_id";
-- [4] (ACCESS EXCLUSIVE) Rename column billing_order.id -> billing_order_id
ALTER TABLE "public"."billing_order" RENAME COLUMN "id" TO "billing_order_id";
-- [5] (ACCESS EXCLUSIVE) Rename column billing_order_tag.id -> billing_order_tag_id
ALTER TABLE "public"."billing_order_tag" RENAME COLUMN "id" TO "billing_order_tag_id";
-- [6] (ACCESS EXCLUSIVE) Rename column billing_orderstatus_type.id -> billing_orderstatus_type_id
ALTER TABLE "public"."billing_orderstatus_type" RENAME COLUMN "id" TO "billing_orderstatus_type_id";
-- [7] (ACCESS EXCLUSIVE) Rename column billing_tag.id -> billing_tag_id
ALTER TABLE "public"."billing_tag" RENAME COLUMN "id" TO "billing_tag_id";
-- [8] (ACCESS EXCLUSIVE) Drop identity on billing_orderstatus_type.billing_orderstatus_type_id
ALTER TABLE "public"."billing_orderstatus_type" ALTER COLUMN "billing_orderstatus_type_id" DROP IDENTITY IF EXISTS;
-- [9] (ACCESS EXCLUSIVE) Alter column type billing_orderstatus_type.code -> text
ALTER TABLE "public"."billing_orderstatus_type" ALTER COLUMN "code" TYPE TEXT;
COMMIT;
-- ===========================================================================
-- PHASE 4 (POST-COMMIT ONLINE / AUTOCOMMIT): CONCURRENTLY & VALIDATE steps
-- Run outside any BEGIN ... COMMIT block (or call pgm.finalize_external()).
-- ===========================================================================
-- [post-1] (NONE) Sync TypeTable seeds for billing_orderstatus_type
-- (Parameterized query executed automatically by pgm.finalize_external())
INSERT INTO "public"."billing_orderstatus_type" ("billing_orderstatus_type_id", "code")
VALUES ($1, $2), ($3, $4), ($5, $6)
ON CONFLICT ("billing_orderstatus_type_id") DO UPDATE SET "code" = EXCLUDED."code";
4. Apply directly with upgrade_schema()#
With zero unmanaged view dependencies, apply ap.plan.ops via pgm.Migration + pgm.upgrade_schema(..., allow_breaking=True, allow_destructive=True, ignore_tables=APP.ignore_tables) (same pattern as SQLAlchemy Step 4), then verify with pgdorm ... status.