Fisrt,这是我的模特:
class Question(models.Model):
description = models.CharField(max_length=200)
analysis = models.CharField(max_length=50)
def __str__(self):
return self.description
class QuestionOption(models.Model):
question = models.ForeignKey(Question,related_name='options')
content = models.CharField(max_length=100)
isAnswer = models.BooleanField()
def __str__(self):
return self.question.description + " " + self.content
我的序列化器:
class QuestionSerializer(ModelSerializer):
class Meta:
model = Question
fields = '__all__'
Serializer
的{{1}}同样
我的ViewSet:
QuestionOption
我想发布一个Json数据,如下所示:
class QuestionViewSet(ModelViewSet):
queryset = Question.objects.all()
serializer_class = QuestionRetriveSerilzer
我希望我的{
"options": [
{
"content": "This is the first option",
"isAnswer": false
},
{
"content": "This is the second option",
"isAnswer": true
}
],
"description": "which one is true?",
"analysis": "It's esay"
}
可以自动为我创建QuestionViewSet
和两个Question
,当我发布Json数据时,QuestionOption
是空列表,所以我覆盖options
的{{1}}方法,如下所示:
create
这种方法可行,但我想找到一种更简单的方法,因为我必须覆盖QuestionViewSet
和其他方法,这不是一件容易的事......
那么如何设计 def create(self, request, *args, **kwargs):
serializer = QuestionSerializer(data=request.data)
question = serializer.save()
for data in request.data['options']:
data['question'] = question.id
optionSeializer = OptionSerializer(data=data)
print optionSeializer.is_valid()
optionSeializer.save()
return Response(serializer.data,status=status.HTTP_200_OK)
和update
以便自动创建对象并使用外键更新对象?