django模型如何正确访问多个字段?

5sxhfpxr  于 2021-09-08  发布在  Java
关注(0)|答案(1)|浏览(480)

对于这两种模型:选择和提交,当我尝试获取提交对象的选择集时,它失败了。我不确定这是由模型或视图引起的。我可以知道正确的方法是什么吗?


# In Models.py

class Question(models.Model):
   question = models.TextField()
   lesson = models.ForeignKey(Lesson, on_delete=models.CASCADE)
   grade = models.IntegerField(default=0)
   course = models.ManyToManyField(Course)

   def is_get_score(self, selected_ids):
      all_answers = self.choice_set.filter(is_correct=True).count()
      selected_correct = self.choice_set.filter(is_correct=True, id__in=selected_ids).count()
      if all_answers == selected_correct:
          return True
      else:
          return False

class Choice(models.Model):
   question = models.ForeignKey(Question, on_delete=models.CASCADE)
   choice = models.TextField()
   is_correct = models.BooleanField()

class Submission(models.Model):
  enrollment = models.ForeignKey(Enrollment, on_delete=models.CASCADE)
  choices = models.ManyToManyField(Choice)

# In views.py

def show_exam_result(request, course_id, submission_id):
   context ={}
   total = 0
   course = course_id
   submission = Submission.objects.get(id=submission_id)
   choice_ids = submission.choice_set.all()
   for choice in choice_ids:
       if choice.is_correct == True:
           total = total + choice.question.grade
   context['course'] = course
   context['selected_ids'] = choice_ids
   context['grade'] = total
   return render(request, 'onlinecourse/exam_result_bootstrap.html', context)

# error message

'Submission' object has no attribute 'choice_set'
vbopmzt1

vbopmzt11#

不需要 _set . 应该是 submission.choices.all()

相关问题