Я получаю сообщение об ошибке при попытке получить объект Вопрос из моего объекта Выбор.
Ошибка: аргумент int () должен быть строкой, байтовоподобным объектом или числом, а не 'Question'
У меня есть две модели:
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
}
]
}