Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Adding db_index to existing table

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?

like image 632
Daniel Avatar asked Oct 17 '25 02:10

Daniel


1 Answers

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

like image 123
2ps Avatar answered Oct 18 '25 17:10

2ps



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!