6. Database Migration

“Migrations are Django’s way of propagating changes you make to your models (adding a field, deleting a model, etc.) into your database schema.”

Migrations | Django documentation

Now that you have created the models, the next step is to create the tables in the database.

6.1. Create the migration

The first step is to create a migration so that Django’s migration framework knows about the new models you created. You do that by running the makemigrations command:

$ python manage.py makemigrations marcador
Migrations for 'marcador':
  0001_initial.py:
    - Create model Bookmark
    - Create model Tag
    - Add field tags to bookmark

This will create the new file 0001_initial.py in the directory migrations of the app marcador:

marcador
|-- __init__.py
|-- admin.py
|-- migrations
|   |-- 0001_initial.py
|   `-- __init__.py
|-- models.py
|-- tests.py
`-- views.py

6.2. Migrate the database

After that you have to apply the migration you just created as well as the already existing migrations to create the database schema by using the migrate command:

$ python manage.py migrate
Operations to perform:
  Synchronize unmigrated apps: staticfiles, messages
  Apply all migrations: admin, contenttypes, marcador, auth, sessions
Synchronizing apps without migrations:
  Creating tables...
    Running deferred SQL...
  Installing custom SQL...
Running migrations:
  Rendering model states... DONE
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying marcador.0001_initial... OK
  Applying sessions.0001_initial... OK

Now all tables defined in the migrations have been created in the database.