ashley parker
ashley parker

Reputation: 55

how to create unique_together index using Uniqueconstraints function in django?

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.

Upvotes: 0

Views: 1835

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477230

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].

Upvotes: 2

Related Questions