Django:用 UniqueConstraint 替换 unique_together

fre*_*erk 2 django unique-constraint

我试图对VoteDjango 应用程序中的模型强制实施约束,即用户不能对同一对象多次投票。

为此,我正在使用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"]
Run Code Online (Sandbox Code Playgroud)

我认为这有效。

然而,在 Django 的文档中指出unique_together

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

如何将上面的代码 using 替换unique_together为代码 using UniqueConstraint

ikl*_*nac 6

只需添加一个UniqueConstraint即可:

class Meta:
    constraints = [
            UniqueConstraint(
                 fields=['user', 'definition'], 
                 name='unique_vote'
            )
    ]
Run Code Online (Sandbox Code Playgroud)