Adding indexes to model fields in Django with migrations

前端 未结 3 1774
灰色年华
灰色年华 2021-02-13 03:11

I am trying to add indexes on model fields using Field.db_index for an app that has migrations. Looking at Django\'s documentation all I need to do is to set

3条回答
  •  有刺的猬
    2021-02-13 03:45

    OK, I managed to create the indexes using Meta.index_together. It is not the cleanest way, since I am not actually indexing multiple fields together but it works with makemigrations:

    class Person(models.Model):
        class Meta():
            index_together = [['last_name']]
        first_name = models.CharField()
        last_name = models.CharField()
    

    Now makemigrations does make a new migration:

    ./manage.py makemigrations app-name
    
    >>Migrations for 'app-name':
    >>  0005_auto_20140929_1540.py:
    >>    - Alter index_together for Person (1 constraint(s))
    

    And the corresponding sql command is actually CREATE INDEX.

    ./manage.py sqlmigrate app-name 0005_auto_20140929_1540
    
    >>BEGIN;
    >>CREATE INDEX app-name_person_last_name_7...4_idx ON `app-name_person` (`last_name`);
    >>COMMIT;
    

提交回复
热议问题