4

I have a Django model where I want to add a db_index=True to a field after the table was created.

I figured out that Django doesn't create a migration, thus the index is not created. If the table is nonexistent and first created, Django creates the index.

I've read Django : db_index and makemigrations, but I wonder if it's a good idea to manually create a migration file?

I'm using MySQL. What's the Django best practice on this?

Daniel
  • 1,515
  • 3
  • 17
  • 30

1 Answers1

11

Yes. It is perfectly okay and acceptable, and (sometimes) even best practice to use a hand-written migration for this. There is even a special command that creates a blank migration just for these types of issues.

python manage.py makemigrations --empty --name create_table_index 

And edit it just like in the example posted in your link:

class Migration(migrations.Migration):

    dependencies = [
        ('your_app', '0001_initial'), # or last mig
    ]

    operations = [
        migrations.RunSQL("CREATE INDEX idx_column ON my_table (my_column)"),
        # this format should also work for mysql
    ]    

For tables that are mission-critical to your application, some ops teams prefer to add the index by hand so that you have more control over the timing of the impact that creating the index will have on the app. But that is usually a matter of team preference

2ps
  • 15,099
  • 2
  • 27
  • 47
  • 2
    Thanks for your answer. I'll try that. I just find it strange that Django's `makemigrations` just doesn't care. I think adding indexes at a later stage in a project is a pretty common case. – Daniel Jan 06 '17 at 07:37
  • 14
    just gona comment on this one... django makemigrations DEFINITELY supports adding indexes after the fact. I thought the same but it turns out I was trying to add an index to a foreignkey related field and django automatically indexes those fields, so setting db_index=True and running makemigrations to those has no effect because they're ALREADY indexed. – bryan60 Jan 22 '18 at 15:48