4

I want to add to existing fields some db_index in my models. I just added db_index=Trueto the model.

I was thinking I would need to run python manage.py migrateto apply them on the database. My issue is that no change is detected thus no migration is created. Is it a normal behavior ?

Or is there a specific behavior I'm not aware of?

Thank you.

Alex Grs
  • 3,231
  • 5
  • 39
  • 58

2 Answers2

1

If you know enough of SQL, you can still create the migration by hand using RunSQL.

For example: (with PostgreSQL syntax)

class Migration(migrations.Migration):

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

    operations = [
        migrations.RunSQL("CREATE INDEX my_table_my_column_ind ON my_table (my_colum)"),
    ]

Related: Creating Partial Indexes with Django 1.7

Community
  • 1
  • 1
stellasia
  • 5,372
  • 4
  • 23
  • 43
0

you can use index_together

class YourModel(models.Model):
    # ...

    class Meta:
        index_together = ["field_that_needs_index"]

then makemigration should work

doniyor
  • 36,596
  • 57
  • 175
  • 260
  • Is there really no way to only add db_index? I have 2 / 3 indexes to create on my models ? – Alex Grs Dec 03 '15 at 18:20
  • set the db_index in the fields also, but you need migration for it, so add these fields in index_together also. – doniyor Dec 03 '15 at 18:28
  • Ok. how can I check then that my indexes are created ? Creating thos index_together will not cause issues with writes / or database size ? – Alex Grs Dec 03 '15 at 18:44
  • @AlexGrs nope, no issues. `SHOW INDEX FROM [tablename]` will show you the indexes from your tables – doniyor Dec 04 '15 at 04:02