Django setup and use migration scheme

After writing the models.py file in Django, according to the created model class, we need to define the database table for it. Django is configured with a migration system to track the changes made by the model and transfer them to the database. Correspondingly, the migrate command can perform migration operations for all applications listed in INSTALLED_APPS and synchronize the corresponding databases (including the current model and existing migration content).

First we need to create an initial migration for our model. In the root directory of the project, you can run the following commands (makemigrations is best followed by an application name, it doesn’t matter if it doesn’t):

python manage.py makemigrations

The corresponding output result is (## is your application name):

Migrations for '##':
  ##/migrations/0001_initial.py
    -Create model ##

Django only generates the 0001_initial.py file in the migrations directory of your application. We can open the file to view the migration results. Migration specifies the dependencies of other migrations and operations performed in the database to facilitate the synchronization of model changes.

Next, synchronize the database with the new model. Run the following command to apply the existing migration:

python manage.py migrate

The corresponding output results are as follows (## is your application name):

Applying ##.0001_initial... OK

We only used migrations for the applications listed in INSTALLED_APPS, including our ##applications. After applying the migration, the database reflects the current state of the model.

When editing the models.py file to add, remove, or modify the fields of an existing model, or add a new method, you need to use the makemigrations command to create a new migration. This migration allows Django to track the changing state of the model. Later, it needs to be applied together with the migrate command to keep the database and model synchronized.

Guess you like

Origin blog.csdn.net/Erudite_x/article/details/112434841