I am developing web systems using Django and they are deployed on Heroku. After the system goes production, all database data and the migration files (i.e., the 00*_* files) have to be retained. The followings are my procedure to perform database migration and deployment:
For the first deployment, perform manage.py makemigrations
locally and push to Heroku.
Perform manage.py migrate
on Heroku.
If models are changed later:
Perform makemigrations
locally and push to Heroku.
Perform migrate
on Heroku.
Steps 3 and 4 are repeated if models are changed.
As the system evolves, there are more and more migration files. I am wondering: after a successful migration and deployment, can I just delete all migration files and start like a fresh one? That is:
For the first deployment, perform makemigration
locally and push to Heroku.
Perform migrate
on Heroku.
Delete all local migration files.
Perform makemigrations
locally to create seemingly start-up migration files.
Change models:
Perform makemigration
locally and push to Heroku.
Perform migrate
on Heroku.
Steps 3 to 6 are repeated if models are changed.
Is the above procedure correct?
Migration files are the history of your database. One migration file is created based on the migration files created in the past. Deleting migration files means losing your history. This historical info is recorded in the django_migrations table in your database.
Deleting Django migrations is generally a bad idea. Django keeps track of what's in your db through these migration files, as well as through a table it creates in your db, and if you delete any of this Django will start throwing errors on migrate that can be hard to fix.
Delete your Migrations folder. Create a new migration and generate a SQL script for it. In your database, delete all rows from the migrations history table. Insert a single row into the migrations history, to record that the first migration has already been applied, since your tables are already there.
For each of your app:
1) Pretend to rollback all existing migrations:
./manage.py migrate app zero --fake
The zero
argument indicates that we rollback to the first migration. You can confirm all migrations have been rollbacked by running ./manage.py migrate app --list
.
The --fake
option signals we should not actually run the migrations, but nonetheless mark the migrations as having been run: https://docs.djangoproject.com/en/1.8/ref/django-admin/#django-admin-option---fake
2). Delete migration files
git rm app/migrations/*
3) Create a new migration file
./manage.py makemigrations app
4) Pretend to run the new migration
./manage.py migrate app --fake
As in 1), step 4) does not actually run the migrations.
EDIT: added some explanations and fixed the zero
argument.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With