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 manage.py
utility when in the project root directory:
python manage.py 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 settings.py
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 manage.py makemigrations --dry-run
To apply the migrations:
python manage.py 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 manage.py 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 manage.py 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.