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?
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',)
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')
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.
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')
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With