0
最前一頁創建對象,這裏是我的模型:如何使用外鍵
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__'
QuestionOption
的Serializer
作爲同一
我的視圖集:
class QuestionViewSet(ModelViewSet):
queryset = Question.objects.all()
serializer_class = QuestionRetriveSerilzer
我要發佈一個JSON數據,如:
{
"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
和兩個QuestionOption
對我來說,當我張貼JSON數據,該options
是空列表,所以我覆蓋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
等方法,它不是一個簡單的任務。 ..
那麼如何設計Serializers
和ViewSet
以便自動創建對象並用外鍵更新對象?
太棒了!非常感謝,這可以工作得很好! – IceLee
不客氣。 – Ykh