Nim*_*ima 10 django django-models django-admin django-migrations django-2.1
我正在尝试使用Field.db_index具有迁移的应用程序在模型字段上添加索引.看看Django的文档我需要做的就是设置db_index=True:
class Person(models.Model):
first_name = models.CharField()
last_name = models.CharField(db_index=True)
Run Code Online (Sandbox Code Playgroud)
然后我首先尝试了新的Django迁移:
./manage.py makemigrations app-name
Run Code Online (Sandbox Code Playgroud)
但是迁移似乎没有注意到更改,也没有添加用于创建索引的sql命令.所以我试着django-admin.py按照这里的解释:
django-admin.py sqlindexes app-name
Run Code Online (Sandbox Code Playgroud)
但是,这也不会打印sql命令,它会退出并出现以下错误:
CommandError: App 'app-name' has migrations. Only the sqlmigrate and sqlflush commands can be used when an app has migrations.
Run Code Online (Sandbox Code Playgroud)
ils*_*005 17
这个问题在django2.1中依然存在。我通过使用索引 Meta option解决了它。这比index_together解决方案更清洁。
class Person(models.Model):
first_name = models.CharField()
last_name = models.CharField()
class Meta:
indexes = [
models.Index(fields=['last_name']),
]
Run Code Online (Sandbox Code Playgroud)
好的,我设法使用创建索引Meta.index_together.这不是最干净的方式,因为我实际上并没有将多个字段编入索引,但它适用于makemigrations:
class Person(models.Model):
class Meta():
index_together = [['last_name']]
first_name = models.CharField()
last_name = models.CharField()
Run Code Online (Sandbox Code Playgroud)
现在makemigrations确实进行了新的迁移:
./manage.py makemigrations app-name
>>Migrations for 'app-name':
>> 0005_auto_20140929_1540.py:
>> - Alter index_together for Person (1 constraint(s))
Run Code Online (Sandbox Code Playgroud)
实际上相应的sql命令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;
Run Code Online (Sandbox Code Playgroud)
您可以在迁移中使用 Django 的AddIndex和Index类明确地执行此操作。
首先创建一个空的迁移,manage.py makemigrations --empty然后简单地填写如下:
from django.db import migrations
from django.db.models.indexes import Index
from django.db.migrations import AddIndex
class Migration(migrations.Migration):
dependencies = [
('app_name', 'ref_to_previous_migration'),
]
operations = [
AddIndex('ModelName', Index(fields=['field_name'], name='my_index'))
]
Run Code Online (Sandbox Code Playgroud)
您可以使用Index类上的选项来指定字段、添加名称以及执行特殊的自定义操作,例如仅索引表的一部分等。检查上面的文档链接。
| 归档时间: |
|
| 查看次数: |
4980 次 |
| 最近记录: |