[Django]-What is Django's migration?

2👍

Migrations are a great way of managing database schema changes. This has 2 main benefits (in my opinion):

1 – If you have multiple instances of an application – development + production being the typical minimum, but could potentially be an application installed by others (either standalone or together with other Django applications), migrations allow you, the developer, to propagate database schema changes in a safe & controlled way. You can guarantee that any up-to-date version of your application (i.e., including your latest database models) will have a functioning database to match. So the general answer is that migrations solve a very common problem in a relatively elegant manner.

2 – Specifically, as noted in another answer, there are initial migrations, even for an absolutely brand-new Django project, relating to users and permissions. Any Django application of any significance that I can think of will need these tables to function – i.e., if you don’t make use of them then you are, arguably, not benefiting from much of what Django has to offer as a framework. By including migrations, you the developer can decide what database to use (SQLite, MySQL, PostgreSQL, etc.) and where that database will reside and once you have made those settings (typically in settings.py for the project), the migrations take care of the rest.

1👍

Those migrations are for the models Django creates by default, such as the users, groups and permissions.

If you’re not going to use them you can comment out those apps in your settings. Otherwise you need to run those migrations to create the required tables for your application.

0👍

The migrate command takes all the migrations that haven’t been applied (Django tracks which ones are applied using a special table in your database called django_migrations) and runs them against your database – essentially, synchronizing the changes you made to your models with the schema in the database.

Migrations are very powerful and let you change your models over time, as you develop your project, without the need to delete your database or tables and make new ones – it specializes in upgrading your database live, without losing data. We’ll cover them in more depth in a later part of the tutorial, but for now, remember the three-step guide to making model changes:

Change your models (in models.py).

Run python manage.py makemigrations to create migrations for those changes

Run python manage.py migrate to apply those changes to the database.

The reason that there are separate commands to make and apply migrations is because you’ll commit migrations to your version control system and ship them with your app; they not only make your development easier, they’re also usable by other developers and in production.

Leave a comment