从Django mod创建复合索引

2024-05-20 09:09:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下型号:

from django.db import models

class PopulationData(models.Model):
    slot = models.IntegerField(db_index=True)
    sample = models.IntegerField()
    value = models.FloatField()

    class Meta:
        unique_together = (('slot', 'sample'),)

我还想在具有UNIQUE约束的列对上创建一个复合索引,如下所示:

CREATE INDEX my_compound_index ON myapp_populationdata (slot, sample);

现在我有一个单独的代码连接到发出前一个SQL语句的post_syncdb信号。有没有办法从型号说明中指出?(注意:我使用的是1.3分支)。


Tags: sampledjangofromimporttruedbindexmodel
3条回答

从django-1.5开始,可以使用index_together元选项生成复合索引: https://docs.djangoproject.com/en/dev/ref/models/options/#index-together

从Django-1.11开始使用Meta.indexes选项https://docs.djangoproject.com/en/1.11/ref/models/indexes/

from django.db import models

class PopulationData(models.Model):
    slot = models.IntegerField(db_index=True)
    sample = models.IntegerField()
    value = models.FloatField()

    class Meta:
        unique_together = (('slot', 'sample'),)
        indexes = [
            models.Index(fields=['slot', 'sample']),
        ]

我认为这在django ORM中还没有实现。

如果您使用迁移工具(如south),它可能是添加该sql语句的好地方,或者如果您预取以避免原始sql,那么您可以使用sqlalchemy(core),但这个例子听起来很简单,只需使用sql即可。

相关问题 更多 >