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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With