how to create unique_together index using Uniqueconstraints function in django?

1.4k Views Asked by At

official document says: UniqueConstraint provides more functionality than unique_together. unique_together may be deprecated in the future. here is my code

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

when i migrate it creates a migrations with message '- Create constraint hello on model helloWorld'. but it is not creating an index on database.

1

There are 1 best solutions below

9
On

Indexing is done through another Meta option: 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'),
        ]

The idea is that being unique together does not per se means you want to index the two (together). Furthermore you can specify for what condition(s) you want to index the fields, by specifing a condition=… parameter [Django-doc].

For more information, seee the model index reference [Django-doc].