You need to enable JavaScript to run this app. Django一对多关系下保存模型出现CheckChoice匹配查询不存在错误如何解决
优惠活动
大模型
产品
解决方案
定价
更多

Django一对多关系下保存模型出现CheckChoice匹配查询不存在错误如何解决

Django问卷功能保存异常解决方案

错误根本原因

  1. 初始版本逻辑缺陷:无论当前问题是单选还是多选,都将拿到的表单值同时查询Choice和CheckChoice两张表,当单选选项的ID不存在于CheckChoice表时就会抛出匹配错误。你遇到的情况就是第一题选项1的ID刚好和某个CheckChoice的ID重合所以未报错,选项3的ID无对应CheckChoice记录直接触发异常。
  2. 更新后的代码仍存在多处逻辑问题:
    • 条件判断if 'question' and 'checkbox' in request.POST逻辑错误,该判断仅检查POST请求中是否存在名为question和checkbox的键,和当前循环的问题无关联,会导致所有问题强制同时查询单选和多选值。
    • 多选值直接用request.POST['checkboxxx']取值只能拿到最后一个选中的选项,无法获取全部勾选结果。
    • QuestionAnswer模型将answer和check_answer同时设为必填外键,不符合业务逻辑:一个问题只能是单选或多选,不可能同时需要两个字段的值。
    • 未给Question添加题型标记,循环处理时无法区分当前问题的类型。

修复步骤

1. 修正模型设计

# 给Question新增题型字段,区分单选/多选
class Question(models.Model):
    TYPE_CHOICES = (
        ('radio', '单选题'),
        ('checkbox', '多选题'),
    )
    survey = models.ForeignKey(Survey, on_delete=models.CASCADE)
    enter_question = models.CharField(max_length=900)
    question_type = models.CharField(max_length=10, choices=TYPE_CHOICES, default='radio')

    def __str__(self):
        return self.enter_question

# 修正QuestionAnswer,两个选项外键允许为空,同一时间只会用到其中一个
class QuestionAnswer(models.Model):
    answer = models.ForeignKey(Choice, on_delete=models.CASCADE, null=True, blank=True)
    check_answer = models.ForeignKey(CheckChoice, on_delete=models.CASCADE, null=True, blank=True)
    survey_answer = models.ForeignKey(SurveyAnswer, on_delete=models.CASCADE)

修改完成后执行python manage.py makemigrations和python manage.py migrate命令同步数据库结构,同时给已有问题设置对应的题型。

2. 修正视图处理逻辑

def survey_fill(request):
    if request.method != 'POST':
        # 此处可补充GET请求的逻辑,比如返回问卷填写页面
        return render(request, 'survey-fill.html')
    ans = SurveyAnswer()
    orig_survey = Survey.objects.get(id=request.POST['survey_id'])
    ans.orig_survey = orig_survey
    ans.save()
    questions = orig_survey.question_set.all()
    for question in questions:
        # 按题型分别处理
        if question.question_type == 'radio':
            # 处理单选题
            qc = request.POST.get(f'question{question.id}')
            if qc:
                qa = QuestionAnswer()
                qa.answer = Choice.objects.get(id=int(qc))
                qa.survey_answer = ans
                qa.save()
        elif question.question_type == 'checkbox':
            # 处理多选题,用getlist获取所有选中的选项ID
            check_ids = request.POST.getlist(f'checkbox{question.id}')
            for check_id in check_ids:
                qa = QuestionAnswer()
                qa.check_answer = CheckChoice.objects.get(id=int(check_id))
                qa.survey_answer = ans
                qa.save()
    return render(request, 'survey-complete.html', {})

优化建议

  • 所有数据库查询操作建议添加异常捕获,或使用get_object_or_404方法,避免非法ID直接抛出500错误。
  • 可使用Django自带的Form或ModelForm做表单校验,减少手动处理表单的逻辑漏洞。

内容的提问来源于stack exchange,提问作者user11766958

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.16 13:54:10