Django模型避免重复

mzaanser  于 2023-02-20  发布在  Go
关注(0)|答案(4)|浏览(151)

在模型中:

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>

如果用户点击保存按钮,上述数据被保存在表中,如何避免重复,即如果用户再次点击同一个提交按钮,不应该有相同值的另一个条目。或者这是必须在视图中处理的事情吗?

jslywgbw

jslywgbw1#

如果单个字段需要唯一,那么只需添加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:

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"]
js81xvg6

js81xvg62#

unique_together也是最好的方法,但是如果它不适合你的需要,你可以用你的表单的clean方法来处理它。

def clean(self):
   try:
      Getdata.objects.get(title=self.cleaned_data['title'], 
                          state=self.cleaned_data['state'],
                          name=self.cleaned_data['name'],
                          created_by=self.cleaned_data['created_by'] )
      #if we get this far, we have an exact match for this form's data
      raise forms.ValidationError("Exists already!")
   except Getdata.DoesNotExist:
      #because we didn't get a match
      pass

   return self.cleaned_data
nwo49xxi

nwo49xxi3#

我认为注入Jquery/JS代码来隐藏保存按钮是个好主意。
创建一个custom_validate. js文件,如下所示,并将其放在目录static(静态文件目录)中

if (!$) {
    $ = django.jQuery;
}

$( document ).ready(function() {
    $("[name=_save]").click(function() {
       $("[name=_save]").css("visibility", "hidden");
    });
});

在www.example.com中admin.py,添加以下代码。

class CustomDataForm(forms.ModelForm):

    class Meta:
        model = GetData

class GetDataAdmin(admin.ModelAdmin):
    # ....
    .....
    form = CustomDataForm

    class Media:
        js = ('/static/custom_validate.js', )
iyfjxgzm

iyfjxgzm4#

我自己也遇到了这个问题,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"]

相关问题