如何解决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_together
。unique_together
将来可能会被弃用。
如何用unique_together
替换上面使用UniqueConstraint
的代码?
解决方法
只需添加一个UniqueConstraint
即可:
class Meta:
constraints = [
UniqueConstraint(
fields=['user','definition'],name='unique_vote'
)
]
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。