Some things you should know about django database migration of migrate

  • 2020-10-23 20:09:13
  • OfStack

The command

The first two commands for database migration are:


python manage.py makemigrations & python manage.py migrate 

The former is to convert the model layer to the migration file migration, while the latter executes the new version of the migration file to update the database.

In both cases, the command invocation defaults to global, which is to operate on all newly changed model or migration files. If you want to operate on part OF app, you append app name:


$ python manage.py makemigrations app_name
$ python manage.py migrate app_name

If you want to be precise to a migration file (0004_xxx.py) :


$ python manage.py migrate app_name 0004

If you want to see the execution status of the migrated file, you can use the showmigrations command:


$ python manage.py showmigrations
admin
 [X] 0001_initial
auth
 [X] 0001_initial
 [X] 0002_alter_permission_name_max_length

Displays the known migrations and status of django.

error

A careless command in a database can sink a hole. In particular, the migrate command, since django's database contains records for migrations, is likely to cause migrate to fail if the migrations file is lost. It is therefore necessary to include migrations files in version control to ensure that the migrations records at development time match the files.

If migrate fails, it is most likely because the migration file contains change information that cannot be completed due to current database constraints. You should go to the data and find the location of these records or keys, delete them and redo them.

1 Generally, these data exist in the following tables: table corresponding to foreign key constraint, auth_permission, django_content_type and django_migrations.


Related articles: