Hari
Hari

Reputation: 1623

Difference between UniqueConstraint vs unique_together - Django 2.2?

I started the new project in Django using version 2.2,which has new constraint unique constraint, Does this same as unique_together or it has any other differences?

Upvotes: 13

Views: 6530

Answers (2)

Mark Mishyn
Mark Mishyn

Reputation: 4151

UniqueConstraint has useful condition.

Just a little example. Let's say you want to check uniqueness for only active products.

class Product(models.Model):
    is_active = models.BooleanField(default=False)
    category_name = models.CharField(max_length=64)
    name = models.CharField(max_length=64)

    class Meta:
        constraints = [
            models.UniqueConstraint(fields=['category_name', 'name'], 
                                    condition=models.Q(is_active=True),
                                    name='category_and_name_uniq')
        ]

Upvotes: 12

Nafees Anwar
Nafees Anwar

Reputation: 6608

Pretty obvious from docs

Use UniqueConstraint with the constraints option instead.

UniqueConstraint provides more functionality than unique_together. unique_together may be deprecated in the future.

Upvotes: 9

Related Questions