I remember when I first started with Django and had to deal with migrations. It wasn't clear to me when I needed to run makemigrations
or migrate
, and would generally always run the commands if things weren't working as expected.
Here is a simple how-to manual that should help you make sense of these commands.
You'll want to run python manage.py makemigrations w
henever you make a change to a model, even if it is updating the description on a field.
Adding or updating functions inside of a model does not need a migration, but you can still run makemigrations
just in case.
If you get 'No changes detected' from the output, you're good to go. Otherwise, you'll see output like this:
Migrations for 'mymodel':
project/app/migrations/0010_auto_20180420_1726.py:
- Alter field title on model1
- Alter field location on model2
Then you will need to do two more steps:
python manage.py migrate
to apply the change to your dataApplying a name to the migration will make it easier to see what each migration was for.
For example:
$ python manage.py makemigrations --name increase_max_lengths
...will create a migration file:
project/app/migrations/0010_increase_max_lengths.py
.
The number is automatically added to the front - this is sequential, and the number will depend on how many migrations you already have.
You will need to migrate whenever new migrations are available that have not yet been applied to the data in the current instance.
These cases would be:
makemigrations
In any of these cases, run:
$ python manage.py migrate
Django's output is helpful on this one. It will tell you if there are no migrations to apply, or even if you need to run makemigrations
when you have changes that aren't in a migration yet.
If you ran a migration that you need to update or change, you may need to go backwards through the migrations.
Let's say you want to 'undo' the migration for 0010_increase_max_lengths.py
that was done earlier.
Specify the app the migration lives in, and the number of the previous migration (full name not necessary):
$ python manage.py migrate app 0009
Replace 'app' with the name of your app. You'll see output that looks like this:
Operations to perform:
Target specific migration: 0009_content_homepage, from app
Running migrations:
Rendering model states... DONE
Unapplying app.0010_increase_max_lengths... OK
Sometimes you may get a message that the migration cannot be unapplied. This is one reason why it's always good to test before running migrations on the production data!