Django models avoid duplicates

后端 未结 3 2363
醉梦人生
醉梦人生 2020-12-14 12:03

In models:

class Getdata(models.Model):
    title = models.CharField(max_length=255)
    state = models.CharField(max_length=2, choices=STATE, default=\"0\")         


        
3条回答
  •  南笙
    南笙 (楼主)
    2020-12-14 12:45

    The unique_together also suggested is the best way, but if that's not appropriate for your needs, you can handle it in your form's clean method. eg

    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
    

提交回复
热议问题