A lot of literature on Django Migration has already been floated over the years. It looks seemingly easy to understand but you can easily get caught in some nasty situation. This article is an attempt to address those situations. The article assumes basic knowledge of python and django is there.
The Premise
There are 3 players in Django Migration
- Models.py file insider your app directory
- Migration folder inside your Django app
- Database table django_migrations inside the database
Models.py file contains various data models. The model definitions will be used to create database tables in the backend. Here is the model definition that we are using here
from django.db import models
class Question(models.Model):
question_txt = models.CharField(max_length=200)<br>
pub_date = models.DateTimeField('date published')
question_answer = models.CharField(max_length=200)
A change flows from the model definitions to the database in 2 steps:
makemigrations command - During this process, a migration file is created for the new change (add, deletion or modification) that has taken place in the model. Lets check the migration folder after the command
$ python manage.py makemigrations polls
Migrations for 'polls':
polls/migrations/0001_initial.py
- Create model Question
At this stage, if we run showmigrations, it will show something like this
$ python manage.py showmigrations polls
polls
[ ] 0001_initial
Let's see the database table also and see the current status. There is no Polls under app
migrate command - The migration file is used to change (create, drop, alter etc) database tables
$ python manage.py migrate polls
Operations to perform:
Apply all migrations: admin, auth, contenttypes,polls, sessions
Running migrations:
Applying polls.0001_initial... OK
Let's see the database now. We can now see polls with 0001_initial
This understanding is very important to fix migration issues and in the right use of --fake-initial and --fake which will be described in later sections.