UniqueConstraint 与 unique_together 之间的区别 - Django 2.2?

Difference between UniqueConstraint vs unique_together - Django 2.2?

我在 Django 中使用版本 2.2 启动了新项目,它有新的约束 unique constraint, Does this same as unique_together 还是有任何其他差异?

docs

来看很明显

Use UniqueConstraint with the constraints option instead.

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

UniqueConstraint 有用 condition.

举个小例子。假设您只想检查活动产品的唯一性。

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')
        ]