Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 717
Hari Avatar asked Apr 03 '19 12:04

Hari


People also ask

What is Unique_together in Django?

What is Unique_together in Django? Django unique_together is used to make two or more model fields to be unique. class MyModel(models.Model): field1 = models.CharField(max_length=50) field2 = models.CharField(max_length=50) field3 = models.CharField(max_length=50) class Meta: unique_together = ('field1', 'field2',)

What is UniqueConstraint in Django?

UniqueConstraint. condition. A Q object that specifies the condition you want the constraint to enforce. For example: UniqueConstraint(fields=['user'], condition=Q(status='DRAFT'), name='unique_draft_user')


2 Answers

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.

like image 85
Nafees Anwar Avatar answered Oct 12 '22 11:10

Nafees Anwar


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')
        ]
like image 23
Mark Mishyn Avatar answered Oct 12 '22 09:10

Mark Mishyn