Django:将Unique_together替换为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,related_name="deFinition_Votes")

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

我认为这可行。

但是,在Django的unique_together中,documentation被注意到

UniqueConstraint提供的功能unique_togetherunique_together将来可能会被弃用。

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

解决方法

只需添加一个UniqueConstraint即可:

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