Sept. 18, 2024

Django Migration Commands in a 100 words

Django's migration system to me is world class, I wouldn't really want to manage a database any other way when I have the choice. The guard rails Django provides are sensible and logical, however I have been doing Django for 12 years so I am biased!

However newcomers to Django often seem to struggle with the migration system and end up having to reset their database from scratch and/or deleting their migration files. With that said I'm going to walk through interacting with the Django migration system.

Before we start, the first golden rule is not to interact with the database outside of Django, this is a common mistake and will often end in tears and wasted time. The second golden rule is to not to delete your migration files, unless you 100% know they haven't been applied to the database.

The first command is makemigrations. This command should only ever be used in development. It creates the migration files by examining the difference between your models.py and the current state of the database and then generates the appropriate commands in a new migration file. Migration files need to be commited to your source control of choice, they the instructions to any new environment of how to setup the project.

The second command is migrate. This command can and should be run in any environment, normally it is run during development and on deployment to other environments. This command will apply any unapplied migrations to the database. This is achieved by comparing the migration files that exist in the codebase to the entries in the django_migration table (Again there is no need to alter this mannually in the normal running of a project). It is worth noting that migrate can rollback migrations as well as apply them. This is useful to fix issues as well as keep a clean migration history during development.

Finally there is showmigrations this will print out a list of all migrations and if they have been applied or not. These are the commands that you will be using on a daily & weekly basis.

Other commands related to migrations are squashmigrations, sqlmigrate and optimizemigration, I have either used these sparingly or never used them. The first three commands are the ones to understand and master.