Django模型避免重复 [英] Django models avoid duplicates

查看:2139
本文介绍了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"]

这篇关于Django模型避免重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆