Skip to content

Instantly share code, notes, and snippets.

@cb109
Last active July 1, 2024 11:36
Show Gist options
  • Save cb109/34b86afc5ed5e573321c20eba363e34b to your computer and use it in GitHub Desktop.
Save cb109/34b86afc5ed5e573321c20eba363e34b to your computer and use it in GitHub Desktop.
Recover from losing Django migration files while preserving the database (tested on Django 3.2)

Let me point out that losing migration files is a very bad situation and should be avoided at all costs, but if it happens, having a step-by-step way to preserve the database is a good thing to have. It is a terrible situation to be in if your database/models/migrations are a shared state across multiple team members, and that would require a coordinated halt and cleanup so everyone can move forward from the same base state again, with a proper migration files workflow from then on.

Let's assume you have models, any number of migration files, all of those applied to your existing database. Now for some reason, poof!, all the migration files are gone.

What you could do:

1. Remove tracked migrations for affected apps

$ python manage.py shell
from django.db.migrations.recorder import MigrationRecorder

MigrationRecorder.Migration.objects.filter(app="app1").delete()
MigrationRecorder.Migration.objects.filter(app="app2").delete()

2. Create new initial migrations representing current state of models and database

$ python manage.py makemigrations app1 app2

Note: Just running python manage.py makemigrations is not sufficient if no <app>/migrations/__init__.py exists, and might tell you there are no changes detected, you want to mention each app explicitly.

Commit and push these files.

3. Let Django think we ran those already

python manage.py migrate --fake-initial app1
python manage.py migrate --fake-initial app2

alternatively we could also have run:

python manage.py migrate --fake

Done, you can now continue making changes to your models, running makemigrations and migrate as usual. Step 1 and 3 would have to be repeated during deployment against your production database.

Be careful, and use at your own risk.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment