【问题标题】:Difference between UniqueConstraint vs unique_together - Django 2.2?UniqueConstraint 与 unique_together 之间的区别 - Django 2.2?
【发布时间】:2019-08-24 23:34:38
【问题描述】:

我在 Django 中使用版本2.2 启动了新项目,它有新的约束unique constraint,这与unique_together 相同还是有其他区别?

【问题讨论】:

标签: django django-models django-queryset python-3.6 django-managers


【解决方案1】:

docs来看很明显

将 UniqueConstraint 与约束选项一起使用。

UniqueConstraint 提供了比 unique_together 更多的功能。 unique_together 将来可能会被弃用。

【讨论】:

  • 当我搜索 unique_together 时,我忘了在 url 中提及 2.2 版。谢谢。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-13
    • 2019-04-09
    • 2014-10-30
    • 2021-12-07
    • 2016-02-09
    • 2016-05-14
    • 2016-10-11
    • 2015-06-02
    相关资源
    最近更新 更多