Django Models Applying the changes to the database (Migrations)

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!


After creating a new model or modifying existing models, you will need to generate migrations for your changes and then apply the migrations to the specified database. This can be done by using the Django's built-in migrations system. Using the utility when in the project root directory:

python makemigrations <appname>

The above command will create the migration scripts that are necessary under migrations subdirectory of your application. If you omit the <appname> parameter, all the applications defined in the INSTALLED_APPS argument of will be processed. If you find it necessary, you can edit the migrations.

You can check what migrations are required without actually creating the migration use the --dry-run option, eg:

python makemigrations --dry-run

To apply the migrations:

python migrate <appname>

The above command will execute the migration scripts generated in the first step and physically update the database.

If the model of existing database is changed then following command is needed for making necessary changes.

python migrate --run-syncdb

Django will create the table with name <appname>_<classname> by default. Sometime you don't want to use it. If you want to change the default name, you can announce the table name by setting the db_table in the class Meta:

from django.db import models

class YourModel(models.Model):
    parms = models.CharField()
    class Meta:
        db_table = "custom_table_name"

If you want to see what SQL code will be executed by a certain migration just run this command:

python sqlmigrate <app_label> <migration_number>

Django >1.10
The new makemigrations --check option makes the command exit with a non-zero status when model changes without migrations are detected.

See Migrations for more details on migrations.

Got any Django Question?