- Django 2 Web Development Cookbook
- Jake Kronika Aidas Bendoraitis
- 328字
- 2021-06-10 19:31:38
How to do it...
To create the database migrations, take a look at the following steps:
- When you create models in your new demo_app app, you have to create an initial migration that will create the database tables for your app. This can be done by using the following command:
(myproject_env)$ python3 manage.py makemigrations demo_app
- The first time that you want to create all of the tables for your project, run the following command:
(myproject_env)$ python3 manage.py migrate
Run this command when you want to execute the new migrations for all of your apps.
- If you want to execute the migrations for a specific app, run the following command:
(myproject_env)$ python3 manage.py migrate demo_app
- If you make some changes in the database schema, you will have to create a migration for that schema. For example, if we add a new subtitle field to the Idea model, we can create the migration by using the following command:
(myproject_env)$ python3 manage.py makemigrations \
> --name subtitle_added demo_app
- Sometimes, you may have to add to or change data in the existing schema in bulk, which can be done with a data migration, instead of a schema migration. To create a data migration that modifies the data in the database table, we can use the following command:
(myproject_env)$ python3 manage.py makemigrations \
> --empty --name populate_subtitle demo_app
This creates a skeleton data migration, which you have to modify to perform the necessary data manipulation before applying it.
Learn more about Writing database migrations in the official How To guide, found at https://docs.djangoproject.com/en/2.1/howto/writing-migrations/.
- To list all of the available applied and unapplied migrations, run the following command:
(myproject_env)$ python3 manage.py showmigrations
The applied migrations will be listed with a [X] prefix. The unapplied ones will be listed with a [ ] prefix.
- To list all of the available migrations for a specific app, run the same command, but pass the app name, as follows:
(myproject_env)$ python3 manage.py showmigrations demo_app