问题描述
我正在尝试在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_together
。unique_together
将来可能会被弃用。
如何用unique_together
替换上面使用UniqueConstraint
的代码?
解决方法
只需添加一个UniqueConstraint
即可:
class Meta:
constraints = [
UniqueConstraint(
fields=['user','definition'],name='unique_vote'
)
]