Search code examples
djangodjango-modelsdjango-migrations

Django: How to migrate to class-based indexes


Django 1.11 introduced Class-based model indexes. What was previously defined as

class A(models.Model):
    class Meta:
        index_together = [
            ('foo', 'bar'),
        ]

Can now be defined as

class A(models.Model):
    class Meta:
        indexes = [
            models.Index(fields=['foo', 'bar']),
        ]

When I change to the new syntax for a model an run python manage.py makemigrations, it will create migrations like

class Migration(migrations.Migration):

    dependencies = [
        ('app', '0001_initial'),
    ]

    operations = [
        migrations.AlterIndexTogether(
            name='a',
            index_together=set([]),
        ),
        migrations.AddIndex(
            model_name='a',
            index=models.Index(fields=['foo', 'bar'], name='app_a_f12345_idx'),
        ),
    ]

This migration will remove and re-create my indexes, which is something I'd like to avoid.

What is the recommended way for switching from the old to the new syntax? I could not find anything in the documentation.


Solution

  • You can edit the generated migration so that the index name matches your original index_together index name, then run manage.py migrate with --fake option.