代码如下
models.py
class Question(models.Model):
lesson = models.ForeignKey(Lesson, on_delete=models.CASCADE, related_name='questions')
question = models.CharField('lesson name', max_length=120)
class Option(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='options')
option = models.CharField('test option', max_length=100)
correct = models.BooleanField(default=False)
views.py
class QuestionAPIView(generics.CreateAPIView):
queryset = Question.objects.all()
serializer_class = QuestionSerializer
serializers.py
class OptionSerializer(serializers.ModelSerializer):
class Meta:
model = Option
fields = ('option', 'correct')
class QuestionSerializer(serializers.ModelSerializer):
options = OptionSerializer(many=True)
class Meta:
model = Question
fields = ('lesson', 'question', 'options')
def create(self, validated_data):
options_data = validated_data.pop('options')
question = Question.objects.create(**validated_data)
for option_data in options_data:
Option.objects.create(question=question, **option_data)
return question
我想创建一个测试问题,有几个选项的答案,像这样:
data = {
"lesson": 2,
"question": "This is our first question?",
"options": [
{
"option": "Option 1",
"correct": True
},
{
"option": "Option 2 ",
"correct": False
},
{
"option": "Option 3",
"correct": True
}
]
}
但是在postman和TestCase中,我有:
{
"options": [
"This field is required."
]
}
验证的问题是什么?
这里是文档:
https://www.django-rest-framework.org/api-guide/relations/writable-nested-serializers
在我的测试中它确实工作得很好。请注意你的JSON对象,你使用True/False作为Python布尔变量,而不是JSON:(测试邮差和DRF可浏览API)
data = {
"lesson": 2,
"question": "This is our first question?",
"options": [
{
"option": "Option 1",
"correct": true
},
{
"option": "Option 2 ",
"correct": false
},
{
"option": "Option 3",
"correct": true
}
]
}