我正在尝试检查并在添加条目之前查看数据库中是否存在重复条目。以下是我目前的型号 -
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。如何修复此问题以及检查重复项时?谢谢。
答案 0 :(得分:2)
首先,除非你有充分的理由,否则你真的不应该访问帖子变量而不通过表格发送它们。
from django import forms
class MyForm(forms.form):
school = forms.CharField()
degree = forms.CharField(required=False)
class_year = forms.CharField(required=False)
def clean(self):
if not self.cleaned_data.has_key('degree'):
self.cleaned_data['degree'] = None
if not self.cleaned_data.has_key('class_year'):
self.cleaned_data['class_year'] = None
return self.cleaned_data
然后当你处理视图时:
...
if request.method == "POST":
form = MyForm(request.POST)
if form.is_valid():
try:
# NOTE that the objects.get method will raise MultipleObjectsReturned if the
# database has more than one object that matches the query
my_object = Education.objects.get(school=form.cleaned_data['school'],
class_year=form.cleaned_data['class_year'],
degree = form.cleaned_data['degree'])
except Education.DoesNotExist:
my_object = Education(school=form.cleaned_data['school'],
class_year=form.cleaned_data['class_year'],
degree = form.cleaned_data['degree'])
else:
form = MyForm()
...
答案 1 :(得分:1)
观点:
if 'Add School' in request.POST.values():
form = EducationForm(request.POST)
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, ValueError):
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()
return redirect('edit_education')
或者,使用get_or_create
来简化:
if 'Add School' in request.POST.values():
form = EducationForm(request.POST)
if form.is_valid() and request.POST['school']:
school = form.cleaned_data['school']
school_object, created = Education.objects.get_or_create(school=form.cleaned_data['school'],
class_year=form.cleaned_data['class_year'],
degree = form.cleaned_data['degree'])
if created:
profile.educations.add(school_object)
profile.save()
return redirect('edit_education')
表格:
YEAR = ([(x, x) for x in range(1970,2015)])
YEAR.append((0,'Select Year'))
YEAR.reverse()
class EducationForm(forms.Form):
school = forms.CharField()
class_year = forms.ChoiceField(choices=YEAR, required=False)
degree = forms.CharField(required=False)
def clean(self):
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