我有两个模型:Exam
和Question
。每个问题都有在每次考试中自动计算的分数。
所以这是我的文件:
#Models.py
class Exam(models.Model):
questions = models.ManyToManyField(Question)
title = models.CharField()
class Question(models.Model):
title = models.CharField()
answer = models.TextField()
points = models.PositiveSmallIntegerField()
#Forms.py
class ExamForm(ModelForm):
class Meta:
model = Exam
fields = '__all__'
#Views.py
if form.is_valid():
new_exam = form.save(commit=False)
# Some modify goes here.
new_exam.save()
form.save_m2m()
return redirect('view_exam')
我确实为此定制了模型save()
方法:Exam
def save(self, *args, **kwargs):
self.point = 0
for question in self.questions:
self.point += question.point
super(Exam, self).save(*args, **kwargs)
但我得到了这个错误:
"<Exam: NewObject>" needs to have a value for field "id" before this many-to-many relationship can be used.
我怎样才能做到这一点而不会引发任何错误?
我的目标:对于每一个新创建的考试,计算这个考试的问题点并将它们放入模型points
领域Exam
。