Reputation: 154682
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
Reputation: 15986
new_field
to MyLargeModel
without db_index=True
and savemakemigrations
to generate a migration that will add new_field
without the index.new_field
in the MyLargeModel
definition and add back db_index=True
makemigrations
to generate the standard migration to add the index to MyLargeModel.new_field
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
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