Django migrations, a typical pattern

While the Django migration system can automatically detect a lot of use cases, there are times when we as developers need to give a bit of guidance to the system to ensure we don't loose any data. The pattern below often occurs when transforming data types in some manner.

The high level steps are as follows:

  1. Introduce new field or model, if required. a. If it's a model add new matching relations alongside the existing relations
  2. Perform a data migration that transforms the data to the new field/model a. Again with a model, remember to migrate all the of the relations as well.
  3. Update all other references in the code base to use the new field/model. Alternatively this can be updating both fields for a time to have a slower migration if required.
  4. Push all of this through to production and check it works ok.
  5. Then remove the old field/model.
  6. Deploy again.
  7. Optionally rename the new field/model if required. This is typicial if you have a field called foo and the new field is called new_foo which at this point is no longer new so should revert to just foo again.

This should help get you out of quite a few more complex situations, and deploying after each step here, will reduce the uncertainly of potential data loss and confusion.