You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django投票API如何成功POST关联Question的Choice并解决参数报错

问题原因

你在Choice模型中定义的关联Question的外键字段名称为poll_question,但调用serializer.save()时传入的关键字参数是question,参数名与模型字段名不匹配,Django ORM创建Choice实例时无法识别该参数,因此抛出报错。

修复方案

方案1(无额外迁移成本,推荐)

直接修改视图中调用save方法的参数名,和模型字段保持一致即可:
找到视图代码中的这一行:

poll_question_choice = serializer.save(question=question)

修改为:

poll_question_choice = serializer.save(poll_question=question)

方案2(调整模型字段名,需要重新生成迁移文件)

如果希望保留参数名question,可以修改Choice模型的外键字段名:

# Choice模型修改外键字段名
class Choice(models.Model):
    # 把poll_question改成question
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    poll_question_choice = models.CharField(max_length=255)
    votes = models.IntegerField(default=0)

修改完成后需要执行python manage.py makemigrations和python manage.py migrate完成数据库字段更新。

可选优化建议
  • 建议恢复视图中被注释的question = get_object_or_404(Question, pk=pk)写法,避免传入不存在的问题ID时直接抛出500错误,自动返回404响应更符合API规范。
  • 可以将ChoiceSerializer改为继承ModelSerializer,不需要手动编写create方法,简化代码:
class ChoiceSerializer(serializers.ModelSerializer):
    class Meta:
        model = Choice
        # 仅返回前端需要的字段,外键poll_question不需要暴露
        fields = ['id', 'poll_question_choice', 'votes']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 12:36:04