【发布时间】:2011-09-13 14:52:04
【问题描述】:
我正在尝试在添加条目之前检查并查看数据库中是否存在重复条目。这是我目前的模型--
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。如何解决这个问题以及检查重复项时?谢谢。
【问题讨论】:
标签: django django-models django-views