【问题标题】:django model how to access ManyToManyFields correctly?django模型如何正确访问ManyToManyFields?
【发布时间】:2021-07-10 00:25:26
【问题描述】:

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

#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'

【问题讨论】:

    标签: python django django-models django-views django-queryset


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-10
      • 2020-11-05
      • 2011-12-01
      • 1970-01-01
      • 2016-03-28
      • 2013-10-15
      • 2022-11-30
      • 2017-12-15
      相关资源
      最近更新 更多