我收到TypeError:“ int()参数必须是字符串,类似字节的对象或数字,而不是'Question'”

时间:2019-04-17 08:15:04

标签: python django api django-rest-framework

当我尝试从我的Choice对象中获取Question对象时出现错误。 错误是:int()参数必须是字符串,类似字节的对象或数字,而不是“问题”

我有两个模型:

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField("date published")

    def __str__(self):
        return self.question_text


class Choice(models.Model):
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)
    question = models.ForeignKey(Question,  related_name='choices', on_delete=models.CASCADE)

    def __str__(self):
        return self.choice_text

这是我的观点:

@api_view(['POST', ])
def selectChoice(request):
    try:
        choice_id = request.query_params.get('choice_id')
        selected_choice = get_object_or_404(Choice, id=choice_id)
        selected_choice.votes += 1
        selected_choice.save()
        questions = get_object_or_404(Question, id=selected_choice.question)
        serializer = QuestionWithAnswer(questions)
        return Response(serializer.data)
    except ValueError as e:
        return Response(e.args[0], status.HTTP_400_BAD_REQUEST)

这是我的序列化器:

class ChoiceSerializer(serializers.ModelSerializer):
    class Meta:
        model = Choice
        fields = ('id', 'votes', 'choice_text','question')


class QuestionWithAnswer(serializers.ModelSerializer):
    choices = ChoiceSerializer(many=True)

    class Meta:
        model = Question
        fields = ('id', 'question_text', 'pub_date','choices')

并且我期望下面的API响应:

{
    "id": 2,
    "question_text": "What's your age?",
    "pub_date": "2019-04-13T05:27:39Z",
    "choices": [
        {
            "id": 4,
            "votes": 15,
            "choice_text": "15",
            "question": 2
        },
        {
            "id": 5,
            "votes": 2,
            "choice_text": "16",
            "question": 2
        },
        {
            "id": 6,
            "votes": 2,
            "choice_text": "17",
            "question": 2
        }
    ]
}

2 个答案:

答案 0 :(得分:2)

您不需要进行get_object_with_404呼叫。 selected_choice.question相关的Question对象,它不是ID。您可以将其直接传递给序列化器。

serializer = QuestionWithAnswer(selected_choice.question)

答案 1 :(得分:1)

您在查询集上使用的是对象而不是ID。您的查询集应如下所示:

questions = get_object_or_404(Question, id=selected_choice.question.id)