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:
$ 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()
$ 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.
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.