检查数据库是否重复了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。如何解决此问题以及在检查重复项时如何解决?谢谢。
没有找到相关结果
已邀请:
2 个回复
誓猎贰
然后,当您处理视图时:
味芯憨
或者,使用ѭ5简化以下内容:
形式: