0

官方文档说:UniqueConstraint 提供了比 unique_together 更多的功能。unique_together 将来可能会被弃用。这是我的代码

class Meta:
    constraints = [models.UniqueConstraint(fields=['token','obj'], name='hello')]

当我迁移时,它会创建一个带有消息“-在模型 helloWorld 上创建约束 hello”的迁移。但它没有在数据库上创建索引。

4

1 回答 1

2

索引是通过另一个Meta选项完成的:indexes[Django-doc]

class MyModel(models.Model):

    # …

    class Meta:
        constraints = [
            models.UniqueConstraint(fields=['token','obj'], name='hello')
        ]
        indexes = [
            models.Index(fields=('token', 'obj'), condition='TRUE'),
        ]

这个想法是,一起唯一并不意味着你想(一起)索引两者。condition=…此外,您可以通过指定参数 [Django-doc]来指定要索引字段的条件。

有关更多信息,请参阅模型索引参考[Django-doc]

于 2020-04-17T17:32:51.387 回答