Understanding Migrations in Django
If you read my previous article, then you know that Django is organized into a project, which is then broken down into apps. Each app is considered as a module and has its own models, views and urls. The models are what determine what your database structure will look like.
Migrations are Django’s way of propagating changes you make to your models (adding a field, deleting a model, etc.) into your database schema. They’re designed to be mostly automatic, but you’ll need to know when to make migrations, when to run them, and the common problems you might run into. ~Django Docs
And as of the view above, there are several commands of which you need to familiarize yourself with.
- makemigrations
Executed by:
python manage.py makemigrations
This command is direly responsible for creating new migrations based on the changes you have made to your models.
2. migrate
Executed by:
python manage.py migrate
This command is simply responsible for applying and unapplying migrations.
3. sqlmigrate
Executed by:
python manage.py sqlmigrate
What this command does is that it displays the SQL statements for a migration. e.g:
INSERT * INTO TABLE *
4. showmigrations
Executed by:
python manage.py showmigrations
This command simply lists all the migrations applied in your project and their statuses.
You should think of migrations as a version control system for your database schema.
makemigrations
is responsible for packaging up your model changes into individual migration files - analogous to commits - andmigrate
is responsible for applying those to your database. ~ Django Docs
That’s it for today, I hope you find the article helpful, and if you do, share to your friends as well.