2 回答
TA贡献1848条经验 获得超10个赞
您没有正确实例化序列化器。
@api_view(['GET', 'POST', ])
def getquestionWithChoices(request):
questions = Question.objects.all()
serializer = QuestionWithAnswer(questions, many=True)
return Response(serializer.data)
并且您的序列化程序也未正确定义:
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')
TA贡献1111条经验 获得超0个赞
这是我的观点:
@api_view(['GET', 'POST', ])
def getquestionWithChoices(request):
questions = Question.objects.all()
serializer = QuestionWithAnswer(questions, many=True)
return Response(serializer.data)
这是我的序列化器:
class ChoiceSerializer(serializers.ModelSerializer):
class Meta:
model = Choice
fields = ('id', 'votes', 'choice_text',)
class QuestionWithAnswer(serializers.ModelSerializer):
question = ChoiceSerializer(many=True)
class Meta:
model = Question
fields = ('id', 'question_text', 'pub_date','question')
这是我的模型:
class Choice(models.Model):
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
question = models.ForeignKey(Question, related_name='question', on_delete=models.CASCADE)
def __str__(self):
return self.choice_text
任何寻找相同的人都可以使用这个。所有剩余的代码都与问题相同。
添加回答
举报