通过迁移为Django中的模型字段添加索引 [英] Adding indexes to model fields in Django with migrations

查看:1372
本文介绍了通过迁移为Django中的模型字段添加索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Field.db_index 为具有迁移的应用程序添加索引。查看 Django的文档所有我需要做的是设置 db_index = True

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 db_index=True:

class Person(models.Model):
    first_name = models.CharField()
    last_name = models.CharField(db_index=True)

然后我第一次尝试新的Django的迁移:

and then I first tried the new Django's Migration:

./manage.py makemigrations app-name

但是Migration似乎没有注意到这个更改,并且没有添加sql命令创建索引。所以我试过 django-admin.py 这里

but Migration does not seem to notice the change and does not add the sql command for creating an index. So I tried django-admin.py as explained here:

django-admin.py sqlindexes app-name

但是,不会打印sql命令,并退出并显示以下错误:

But that does not print the sql command either and it exits with the following error:

CommandError: App 'app-name' has migrations. Only the sqlmigrate and sqlflush commands can be used when an app has migrations.


推荐答案

好的,我设法使用 Meta.index_together 。这不是最干净的方法,因为我实际上并不是将多个字段编入索引,而是与 makemigrations 一起使用:

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()

现在 makemigrations 确实进行了新的迁移:

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

相应的sql命令实际上是 CREATE INDEX

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;

这篇关于通过迁移为Django中的模型字段添加索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆