David Wolever
David Wolever

Reputation: 154682

Django migrations: create a partial index and set `db_index=True` without creating a full index?

I'm adding a NULL column to a large table, and I'd like to make sure that it has db_index=True set in the model definition:

class MyLargeModel(Model):
    new_field = IntegerField(null=True, default=None, db_index=True)

But for the actual index I'd like to use a partial index:

migrations.RunSQL("""
    CREATE INDEX my_index
    ON mylargemodel (new_field)
    WHERE new_field IS NOT NULL
""")

However, by default, this will mean Django's migrations will create an index (which will be very slow), then I'll need to manually drop that index and create my own.

How can I create a migration which will tell Django Migrations that db_index=True is set without creating the index in the database?

Upvotes: 1

Views: 945

Answers (1)

2ps
2ps

Reputation: 15986

  1. Add new_field to MyLargeModel without db_index=True and save
  2. run makemigrations to generate a migration that will add new_field without the index.
  3. Update new_field in the MyLargeModel definition and add back db_index=True
  4. run makemigrations to generate the standard migration to add the index to MyLargeModel.new_field
  5. Update the migration from (4) by adding the following custom class to the top of the file:

    from django.db import migrations, models
    
    class NoopAlterField(migrations.AlterField):
        def database_forwards(self, app_label, schema_editor, from_state, to_state):
            pass
    
  6. Update the migration from (4) by changing the call from migration.AlterField to our custom NoopAlterField

    operations = [
        NoopAlterField(
            model_name='mylargemodel',
            name='new_field',
            field=models.IntegerField(...),
        ),
    ]
    

As you can guess all that this does is creates a NoopAlterField migration handler that will update the internal schema tracker but forego the actual database step of creating the index.

Upvotes: 3

Related Questions