Django:用 UniqueConstraint 替换 unique_together

Django: substitute unique_together with UniqueConstraint

我试图在我的 Django 应用程序中对 Vote 模型施加约束,即用户不能对同一对象投票超过一次。

为此,我使用 unique_together:

class Vote(models.Model):
    vote = models.SmallIntegerField(choices=VOTES, null=True, blank=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE,
        related_name="user_votes")
    definition = models.ForeignKey(Definition, on_delete=models.CASCADE,
        related_name="definition_votes")

    class Meta:
        # Ensure user cannot vote more than once.
        unique_together = ["user", "definition"]

我认为这可行。

然而,在 Django 的 documentation for unique_together 中注意到

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

如何用 UniqueConstraint 的代码替换上面使用 unique_together 的代码?

只需添加一个 UniqueConstraint 即可:

class Meta:
    constraints = [
            UniqueConstraint(
                 fields=['user', 'definition'], 
                 name='unique_vote'
            )
    ]

最大的困惑是 UniqueConstraint 文档可以直接从 unique_togther 获得,但它跳过了 Metas.constraint 文档:

constraints

Options.constraints

A list of constraints that you want to define on the model:
from django.db import models

class Customer(models.Model):
    age = models.IntegerField()

    class Meta:
        constraints = [
            models.CheckConstraint(check=models.Q(age__gte=18), name='age_gte_18'),
        ]

示例代码快速告诉您如何使用约束。