oro*_*aki 20 python django django-models database-indexes
模型上的字段foo = models.ForeignKey(Foo)将自动为列添加数据库索引,以便更快地查找.这很好,但Django的文档没有说明模型元中的字段是否unique_together接受相同的处理.我碰巧有一个模型,其中列出的一个char字段unique_together需要一个快速查找索引.我知道db_index=True在字段定义中添加副本不会有任何损害,但我很好奇.
unique_together 不会自动为列表中包含的每个字段添加索引。
新版本的 Django 建议改用索引和约束元选项:
https://docs.djangoproject.com/en/2.2/ref/models/options/#unique-together
https://docs.djangoproject.com/en/2.2/ref/models/options/#index-together
在Django 1.5及更高版本中,您可以使用{Model}.Meta.index_togetherclass属性。如果您有两个名为foo和的字段bar,则可以添加:
class Meta(object):
index_together = unique_together = [
['foo', 'bar']
]
Run Code Online (Sandbox Code Playgroud)
如果只有一组唯一字段,则可以对使用一维可迭代unique_together。但是,文档中没有指出index_together。
这也可以:
class Meta(object):
unique_together = 'foo', 'bar'
index_together = [
['foo', 'bar']
]
Run Code Online (Sandbox Code Playgroud)
但是,文档不支持此功能:
class Meta(object):
unique_together = 'foo', 'bar'
index_together = 'foo', 'bar'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6521 次 |
| 最近记录: |