Django模型避免重复
问题描述:
在模型中:
class Getdata(models.Model):
title = models.CharField(max_length=255)
state = models.CharField(max_length=2, choices=STATE, default="0")
name = models.ForeignKey(School)
created_by = models.ForeignKey(profile)
def __unicode__(self):
return self.id()
在模板中:
<form>
<input type="submit" value="save the data" />
</form>
如果用户点击保存按钮,上述数据保存在表格中,如何避免重复,即如果用户再次点击相同的提交按钮,则不应该有相同值的另一个条目。或者是需要在视图中处理的东西?
If the user clicks on the save button and the above data is saved in the table, how to avoid the duplicates, i.e. if the user again clicks on the same submit button there should not be another entry for the same values. Or is it something that has to be handled in views?
答
如果一个字段需要是唯一的,那么你只需要添加 unique = True
:
If an individual field needs to be unique, then you just add unique=True
:
class Getdata(models.Model):
title = models.CharField(max_length=255, unique=True)
state = models.CharField(max_length=2, choices=STATE, default="0")
name = models.ForeignKey(School)
created_by = models.ForeignKey(profile)
如果要组合字段是唯一的,您需要 unique_together :
If you want a combination of fields to be unique, you need unique_together:
class Getdata(models.Model):
title = models.CharField(max_length=255)
state = models.CharField(max_length=2, choices=STATE, default="0")
name = models.ForeignKey(School)
created_by = models.ForeignKey(profile)
class Meta:
unique_together = ["title", "state", "name"]