Retry Django Data Migration

How to restart data migration to Django 1.8+? If appropriate, my migration is numbered 0011_my_data_migration.py and is the last migration.

+18
source share
2 answers

Return to the migration before the one you want to repeat.

./manage.py migrate --fake yourapp 0010_my_previous_data_migration 

Then restart the migration.

 ./manage.py migrate your app 0011_my_data_migration 

Then you can fake the previous migration that you performed. In your case, you said 0011 was the last, so you can skip this step.

 ./manage.py migrate --fake yourapp 0014_my_latest_data_migration 

Please note that depending on the state of your database and the contents of the migration, re-migration, for example, may result in errors. Note the warning in the docs about the --fake option:

This is intended for advanced users to directly manage the current state of migration if they manually apply the changes; it should be warned that using --fake carries the risk of moving the migration status table to a state in which manual recovery is required for the migration to work correctly.

+44
source

Alasdair's answer gives you a disclaimer, but reverting to a previous migration is only safe if your migration is idempotent, which means you can run it several times without side effects such as duplicate data. Most people do not write their migrations this way, but this is good practice.

You have two ways to make this process safe:

  • Make your data migrations idempotent. This means that any data created is either reused (for example, using the Model.objects.get_or_create() method), or deleted and recreated. Reuse is the best option since deleting and re-creating will change indexes and database sequences.
  • Make backward data migration. You can do this by passing 2 functions in migrations.RunPython() . For example, if you have migrations.RunPython(add_countries) , you should change this to migrations.RunPython(add_countries, remove_countries) and remove any relevant countries in the second function.

If you choose option number 2, you run:

 ./manage.py migrate yourapp 0010_my_previous_data_migration ./manage.py migrate yourapp 0011_my_data_migration 

If you want to make one liner so that it can be used again and again:

 ./manage.py migrate --fake yourapp 0010_my_previous_data_migration && ./manage.py migrate yourapp 0011_my_data_migration 
+4
source

Source: https://habr.com/ru/post/1236515/


All Articles