我现在正在尝试我的第一个Django项目,并且遇到以下问题:当我尝试使用重复的复合主键创建对象时,我的应用程序反应异常。起始情况如下:
为了能够清楚地确定我的成绩,我使用了由唯一的学生ID(matriculation_number
)和唯一的考试ID(exam_id
)组成的复合主键。这是我的models.py文件中的相应模型:
class Result(models.Model):
# No student should be able to be deleted as long as there are still results to show.
matriculation_number = models.ForeignKey(Student, on_delete=models.PROTECT, verbose_name='Matrikelnummer')
# No student should be able to be deleted as long as there are still results to show.
exam_id = models.ForeignKey(Exam, on_delete=models.PROTECT, verbose_name='Prüfungsnummer')
grade = models.DecimalField(max_digits=3, decimal_places=2, default=None,
validators=[MaxValueValidator(6), MinValueValidator(1)],
verbose_name='Note')
# Workaround for composite primary-key
# Get Data using Result.objects.get(matriculation_number=”10”,exam_id=”125”)
class Meta:
unique_together = (('matriculation_number', 'exam_id'),)
verbose_name = 'Ergebnis'
verbose_name_plural = 'Ergebnisse'
要完全获得复合主键,我将变通办法与unique_together
一起使用。以下views.py和Forms.py部分也属于它:
views.py
class ResultCreateView(generic.CreateView):
form_class = CreateResultForm
template_name = 'studentmanager/result/result_create_form.html'
success_url = reverse_lazy('studentmanager:result')
forms.py
class CreateResultForm(forms.ModelForm):
class Meta:
model = Result
fields = ['exam_id', 'matriculation_number', 'grade']
widgets = {
'exam_id': forms.Select(choices=Exam.objects.all(), attrs={'class': 'form-control'}),
'matriculation_number': forms.Select(choices=Student.objects.all(), attrs={'class': 'form-control'}),
'grade': forms.NumberInput(attrs={'class': 'form-control'})
}
如果我现在创建一个全新的结果,那么一切都会正常进行。但是,如果我尝试为同一学生和同一考试输入新的分数,则POST查询将使用代码200触发,但是我将不会重定向到我的success_url,也不会更新数据。甚至没有错误出现。我希望表格显示一个错误,指示所选组合已经存在一条记录。
如何实施这样的验证,以防止为现有的组合键创建重复的新条目,但是相应的错误已出现在表单中?