# Migrate Django from SQLite to PostgreSQL

> Keep Django record URLs, foreign keys, and retired IDs intact when moving a SQLite app to PostgreSQL.

Build the PostgreSQL schema with Django migrations, load the SQLite rows with their primary keys intact, and verify the routes that use those keys. If deleted IDs must stay retired, also carry over the old SQLite sequence's high-water mark. Keeping only the largest surviving ID is not always enough.

For example, suppose projects **7** and **120** still exist, and a task points to project **120**. You once issued project **500**, then deleted it. The migration should leave both existing project URLs intact, preserve the task's foreign key, and keep `/projects/500` missing. The first new project should get an ID above **500**.

## Rehearse with the sample Django app

[Download the Django SQLite cutover starter](https://gregale.dev/examples/django-sqlite-postgres.zip) and unpack it. It contains a synthetic fixture and sequence manifest exported from one consistent SQLite snapshot. The checked-in example contains neither a live database nor customer data.

You need the [Gregale CLI](https://gregale.dev/docs/install.md), Python 3 for the smoke script, and room for a disposable app and managed PostgreSQL database. Use a unique name and an available region. Run these from the starter directory:

```sh
APP=your-unique-django-cutover-demo
DB="$APP-db"
gregale deploy --name "$APP" --create-only --require-authn
gregale postgres create "$DB" --region us-east-2 --postgres-major 17 --class development --scale-to-zero
gregale postgres get "$DB"
```

When the database is ready, bind it with two separate credentials and deploy:

```sh
gregale postgres attach "$DB" "$APP" --env DATABASE_URL --access read_write
gregale postgres attach "$DB" "$APP" --env MIGRATION_DATABASE_URL --access migration
gregale deploy --name "$APP" --require-authn --rollout immediate --wait
```

Immediate routing is for this disposable app only. Keep request authentication enabled: the sample does not implement end-user accounts. The release command runs `migrate`, imports only the bundled demo fixture into an empty target, checks the imported IDs and relationship, and records a receipt. On a redeploy, the receipt prevents the same fixture from being loaded or the sequence from being reset again. The API uses only `DATABASE_URL`; see [separate the migration and runtime roles](https://gregale.dev/docs/postgres-migration-role-vs-app-role.md).

## Check the old links, retired link, and first new ID

Use the HTTPS platform URL from the deploy and export a request credential for the disposable app's owning workspace as `FAAS_TOKEN`. Do not put the credential in the starter or send it to a custom endpoint.

```sh
python3 smoke.py "https://YOUR-APP.gregale.app" v1
```

This checks that the app serves project IDs **7** and **120**, task **21** still points to **120**, and `/projects/500` returns the app's own 404. It posts a project, expects an ID greater than **500**, and reads the row back. It also checks that the serving process did not receive the migration binding and that an anonymous request is denied.

To check a redeploy, change the `revision` literal in `cutover/urls.py` from `v1` to `v2`, deploy to the same disposable app and database, then run:

```sh
gregale deploy --name "$APP" --require-authn --rollout immediate --wait
python3 smoke.py "https://YOUR-APP.gregale.app" v2
```

The v2 check reads the exact project written by v1, using its local `marker.json` receipt. Do not delete the receipt to retry an uncertain POST: use a fresh disposable setup if the write's outcome is unknown.

**Verified on Gregale:** The old IDs and foreign key were unchanged, project 500 still returned 404, and the first new project got ID 501. It was readable after a second deployment. Both releases kept the migration credential out of the serving process. The test used synthetic data, not a live Replit or Fly.io app.

## Why keeping the old sequence value matters

Django's SQLite `AUTOINCREMENT` IDs track a high-water mark in [`sqlite_sequence`](https://sqlite.org/autoinc.html). Deleting ID 500 leaves that value in place. On PostgreSQL, Django's fixture loader resets generated sequences based on the **largest imported row**. For this fixture, the usual reset would leave the next project ID at 121, so automatic inserts could eventually assign 500 again.

The example records the SQLite floor from the same frozen snapshot that produced `rows.json`. After running `loaddata`, and before allowing any target writes, it sets each allowlisted PostgreSQL sequence to at least the source floor, the largest imported ID, and the target sequence's pre-load position if it has already issued an ID. For the sample, that makes the first new project ID **501**. PostgreSQL [sequence changes](https://www.postgresql.org/docs/17/functions-sequence.html) are visible immediately and do not roll back, so fence target writers during the import and do not re-run `loaddata` during ordinary deploys.

To regenerate and inspect the synthetic fixture locally, create a virtual environment, install `requirements.txt`, then run `python export_demo.py /path/to/empty-directory`. Compare `floors.json` with the primary keys in `rows.json`.

## Cut over a real app

1. **Inventory the data and URLs.** Keep explicit primary keys for models whose routes use them. Do not use `dumpdata --natural-primary` for those models; it can omit their primary keys. Use natural foreign keys selectively for generated objects such as content types where appropriate, and rehearse auth, permissions, custom managers, and relationships on a private target. Django's [fixture commands](https://docs.djangoproject.com/en/5.2/ref/django-admin/#dumpdata) explain the export options, including `--all` to bypass a filtering default manager.
2. **Fence source writes and take a final consistent backup.** Include committed WAL-backed changes using [SQLite's backup API](https://www.sqlite.org/backup.html), rather than copying just the database file from a running service. Capture the rows and the ID floor from the same snapshot. Keep the export, credentials, and real customer data out of Git, container images, and build artifacts.
3. **Import once into a private, writer-fenced target.** Run schema migrations first. Validate row counts, representative rows, and exact IDs and relationships; then restore historical floors where needed. The starter's loader and receipt are specific to the synthetic fixture; adapt and test a separate import for your models. This handles ordinary auto-assigned integer IDs, not manual rewrites of IDs or slug changes.
4. **Switch traffic last.** Verify representative URLs, a retired URL, and the first new write with staging data. Keep the old source read-only through the cutover. If you switch back after accepting new writes, reconcile them before the old system is allowed to write again.

For more on the hosting transition, see [deploy Django](https://gregale.dev/docs/deploy-django.md), [migrate from Replit](https://gregale.dev/docs/migrate-from-replit.md), or [migrate from Fly.io](https://gregale.dev/docs/migrate-from-fly.md). When you are done with the disposable exercise, remove only the app and database you created:

```sh
gregale app delete "$APP" --delete-bindings
gregale postgres delete "$DB"
```

Source: https://gregale.dev/docs/migrate-django-sqlite-to-postgres
