在Django测验应用中验证用户选项正确性及统计答对题数方法
嘿,我来帮你搞定这两个Django测验应用的问题!先看你的模型代码,我注意到CorrectChoice的定义没写完,而且Choice里的外键字段名有点语义混淆,先给你补一个合理的版本——毕竟要准确判断答案对错,模型的关联逻辑得清晰才行:
from django.db import models from django.contrib.auth.models import User class Question(models.Model): question_text = models.CharField(max_length=15000) def __str__(self): return self.question_text class Choice(models.Model): # 把原字段名`choice`改成`question`,语义更清晰 question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name="choices") choice_text = models.CharField(max_length=15000) def __str__(self): return self.choice_text class CorrectChoice(models.Model): # 用OneToOneField确保每个题目只有一个正确选项(如果是多选可以改成ForeignKey) question = models.OneToOneField(Question, on_delete=models.CASCADE, related_name="correct_choice") choice = models.ForeignKey(Choice, on_delete=models.CASCADE) def __str__(self): return f"Correct for {self.question.question_text[:20]}..." # 可选:如果需要记录用户答题历史,新增这个模型 class UserAnswer(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE) selected_choice = models.ForeignKey(Choice, on_delete=models.CASCADE) submitted_at = models.DateTimeField(auto_now_add=True)
问题1:如何检查考生所选的选项是否正确?
其实逻辑很直接:当用户提交答案后,拿用户选中的Choice实例,和对应题目绑定的CorrectChoice里的选项做对比就行。
举个视图里的实操例子,假设用户通过POST提交答案,每个题目的表单name格式是question_<题目ID>,值是所选选项的ID:
from django.shortcuts import render from .models import Question, Choice, CorrectChoice def submit_quiz(request): if request.method == "POST": # 遍历所有提交的答题数据 for key, value in request.POST.items(): if key.startswith("question_"): question_id = key.split("_")[1] try: # 获取当前题目、用户选的选项 question = Question.objects.get(id=question_id) user_selected = Choice.objects.get(id=value) # 获取该题的正确选项 correct_option = question.correct_choice.choice # 判断对错 is_correct = user_selected == correct_option # 这里可以做你需要的操作:比如标记对错、临时存到列表里等 print(f"题目{question_id}:{'答对了' if is_correct else '答错了'}") except (Question.DoesNotExist, Choice.DoesNotExist, CorrectChoice.DoesNotExist): # 处理找不到对应数据的异常情况 continue # 后续跳转结果页等逻辑 return render(request, "quiz/result.html") # GET请求返回答题页面 return render(request, "quiz/take_quiz.html")
问题2:如何统计用户答对的题目数量?
分两种场景来处理,看你是否需要保存用户的答题记录:
场景1:实时统计(不保存答题记录)
在提交答案的视图里直接加个计数器,每判断出一个正确答案就+1:
def submit_quiz(request): if request.method == "POST": correct_count = 0 # 获取当前测验的总题数(也可以根据你实际的测验范围调整) total_questions = Question.objects.count() for key, value in request.POST.items(): if key.startswith("question_"): question_id = key.split("_")[1] try: question = Question.objects.get(id=question_id) user_selected = Choice.objects.get(id=value) correct_option = question.correct_choice.choice if user_selected == correct_option: correct_count += 1 except (Question.DoesNotExist, Choice.DoesNotExist, CorrectChoice.DoesNotExist): continue # 把统计结果传给模板展示 context = { "correct_count": correct_count, "total_questions": total_questions, "score": (correct_count / total_questions) * 100 if total_questions > 0 else 0 } return render(request, "quiz/result.html", context) return render(request, "quiz/take_quiz.html")
场景2:基于保存的答题记录统计
如果用了上面的UserAnswer模型保存了用户的答题历史,直接用Django ORM就能快速统计:
from django.db.models import Count def user_quiz_score(request, user_id): # 统计用户答对的题目数量 correct_count = UserAnswer.objects.filter( user_id=user_id, # 筛选出用户选的选项在正确选项列表里的记录 selected_choice__in=CorrectChoice.objects.values("choice") ).count() # 统计用户总共答过的不同题目数量(避免重复答题的干扰) total_answered = UserAnswer.objects.filter(user_id=user_id).values("question").distinct().count() context = { "correct_count": correct_count, "total_answered": total_answered } return render(request, "quiz/user_score.html", context)
内容的提问来源于stack exchange,提问作者Dhruv Shrivastava
相关产品推荐
相关产品推荐

