我想在添加條目之前檢查數據庫中是否有重複條目。這裏是我目前的型號 -檢查數據庫是否與Null字段重複
class Education(models.Model):
school = models.CharField(max_length=100)
class_year = models.IntegerField(max_length=4, blank=True, null=True, choices=YEAR)
degree = models.CharField(max_length=100, blank=True, null=True)
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
employments = models.ManyToManyField(Employment)
在窗體上,用戶必須進入學校。年級和學位是可選的。要檢查重複條目,現在我有 -
if form.is_valid() and request.POST['school']:
school = form.cleaned_data['school']
try:
school_object = Education.objects.get(school=form.cleaned_data['school'],
class_year=form.cleaned_data['class_year'],
degree = form.cleaned_data['degree'])
except (Education.DoesNotExist):
school_object = Education(school=form.cleaned_data['school'],
class_year=form.cleaned_data['class_year'],
degree = form.cleaned_data['degree'])
school_object.save()
profile.educations.add(school_object)
profile.save()
如果沒有填寫class_date,我得到一個ValueError。如何解決這個問題,以及在檢查重複的時候?謝謝。
這並不能解決class_year有空/無域的問題。它仍然會爲基數爲10()的無效文字創建一個ValueError。任何其他想法? – David542 2011-06-13 03:01:40
我改變了清潔方法,如下,現在的作品: 'if not self.cleaned_data.get('class_year'):' 'self.cleaned_data ['class_year'] = None' 'if not self.cleaned_data .get('degree'):' 'self.cleaned_data ['degree'] =''' 'return self.cleaned_data' – David542 2011-06-13 03:12:22