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?
Asked
Active
Viewed 4,756 times
10

Hari
- 1,545
- 1
- 22
- 45
-
5https://docs.djangoproject.com/en/2.2/ref/models/options/#unique-together – Daniel Roseman Apr 03 '19 at 12:32
-
1@DanielRoseman got it thanks, when i search about unique_together i forgot to mention version 2.2 in url. – Hari Apr 03 '19 at 12:36
2 Answers
10
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')
]

Mark Mishyn
- 3,921
- 2
- 28
- 30
6
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.

Nafees Anwar
- 6,324
- 2
- 23
- 42
-
1when i search about unique_together i forgot to mention version 2.2 in url., thanks. – Hari Apr 03 '19 at 12:37