Python – Django reruns operations in migrations

Django reruns operations in migrations… here is a solution to the problem.

Django reruns operations in migrations

In my model, I set the field to unique and migrated it. Then on the production server, this migration crashed because the database had duplicate keys. So I added the following code to the migration:

def remove_duplicates(apps, schema_editor):
    Dir = apps.get_model('myapp.projects.models', 'Dir')

for row in Dir.objects.all():
        if Dir.objects.filter(dir_url=row.dir_url).count() > 1:
            row.delete()

class Migration(migrations. Migration):

dependencies = [
        ('projects', '0021_auto_20180412_1215'),
    ]

operations = [
        migrations. RunPython(remove_duplicates),
        migrations. AlterField(
            model_name='dir',
            name='dir_url',
            field=models. TextField(unique=True),
        ),
    ]

But how to test if this code works on my local machine? When I run manage.py migrate again, my function is not executed and I get the message:

Running migrations: No migrations to apply.

Solution

You can roll back the migration locally and then reapply it.

The last migration of this dependency was 0021_auto_20180412_1215, so you can roll back to that state:

manage.py migrate 0021

Then run manage.py migrate and it will apply this new migration again.

From documentation :

migrate <app_label> <migrationname> : Brings the database schema to a state where the named migration is applied, but no later migrations in the same app are applied. This may involve unapplying migrations if you have previously migrated past the named migration.

Related Problems and Solutions