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?

3
  • Django certainly should create a migration for you when you do makemigrations. Commented Jan 6, 2017 at 8:50
  • 1
    It doesn't and the author of the other post also experiences that. Commented Jan 6, 2017 at 12:32
  • Django does add indexes in normal situations via a migration... Commented Jan 31, 2023 at 19:44

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.