[Django]-Revert Django 1.7 RemoveField migration

31👍

You can manually edit your migration and add AlterField with default value for a field just before RemoveField. It should be safe even after applying migration. That will make RemoveField that will happen after to be reversible.

An example. Having field in model summary named profit that was defined before removal like that:

profit = models.PositiveIntegerField(verbose_name='profits')

you should add before RemoveField of it an AlterField like that:

migrations.AlterField(
    model_name='summary',
    name='profit',
    field=models.PositiveIntegerField(verbose_name='profits', default=0),
    preserve_default=False,
    ),

5👍

If you’re trying to make future migrations reversible, you could try removing the field as three migrations.

  1. Make the field nullable
  2. Data migration. Forward, don’t do anything. Backwards, convert nulls to a stub value.
  3. Remove the field

Each of these three steps should be reversible.

If you have already run the migration and need to reverse it, you could

  1. manually add the field, allowing nulls
  2. convert nulls to a stub value
  3. manually add the not null constraint
  4. Migrate with --fake to the previous migration

1👍

The easiest way may be to use migrations.RunSQL

You can edit the migration so your operations list would look like this:

operations = [
    sql=[('alter table foo_test drop test)],
    reverse_sql=[('alter table foo_test add test varchar)]
]

That would be a hacky solution, but so would be probably any other.

1👍

Just add ‘default’ and ‘preserve_default’ to your AddField or AddModel in older migration, Django will already know that it must recreate the column with the provided default

This Helped me

Leave a comment