我有两个模型,它们是问题和与该问题一致的一组选择。我想结合这两个模型来创建一个 API,显示一个问题列表和他们的选择。
这些是我的模型:
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, on_delete=models.CASCADE)
def __str__(self):
return self.choice_text
这些是我的序列化程序
class QuestionSerializer(serializers.ModelSerializer):
class Meta:
model = Question
fields = ('question_text',)
class ChoiceSerializer(serializers.ModelSerializer):
class Meta:
model = Choice
fields = ('choice_text','question',)
class QuestionWithAnswer(serializers.ModelSerializer):
question = QuestionSerializer(many=True)
class Meta:
model = Choice
fields = ('question',)
这是视图类
@api_view(['GET', 'POST', ])
def getquestionWithChoices(request):
question = Question.objects.all()
serializer = QuestionWithAnswer
return Response(serializer.data)
我尝试了很多东西,但无法获得以下输出。
[
{
"id": 1,
"question_text": "What's your name?",
"pub_date": "2019-04-13T05:27:21Z",
"choices": [
{
"id": 1,
"choice_text": "fred",
"votes": 0,
"question": 1
},
{
"id": 2,
"choice_text": "bob",
"votes": 0,
"question": 1
},
{
"id": 3,
"choice_text": "rachel",
"votes": 0,
"question": 1
}
]
},
慕桂英546537
catspeake
相关分类