Я хочу создать API Quiz Rest, где я могу публиковать данные двойного вложенного сериализатора и также обновлять их
models.py
from django.db import models
class Quiz(models.Model):
name = models.CharField(max_length=1000)
questions_count = models.IntegerField(default=0)
description = models.CharField(max_length=70)
created = models.DateTimeField(auto_now_add=True, null=True, blank=True)
class Meta:
ordering = ('created',)
verbose_name = 'quiz'
verbose_name_plural ='Quizzes'
def __str__(self):
return str(self.name)
@property
def questions(self):
return self.question_set.all()
class Question(models.Model):
quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE)
label = models.CharField(max_length=1000)
order = models.IntegerField(default=0)
def __str__(self):
return self.label
@property
def answers(self):
return self.answer_set.all()
class Answer(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
text = models.CharField(max_length=1000)
is_correct = models.BooleanField(default=False)
def __str__(self):
return self.text
views.py
class QuizAPIView(generics.ListAPIView, mixins.CreateModelMixin):
permission_classes = []
serializer_class = QuizSerializer
queryset = Quiz.objects.all()
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
serializers.py
from rest_framework import serializers
from question.models import Question, Quiz, Answer
class AnswerSerializer(serializers.ModelSerializer):
class Meta:
model = Answer
fields = ['id', 'text', 'is_correct']
class QuestionSerializer(serializers.ModelSerializer):
answers = serializers.ListField(
child=serializers.DictField(), required=True)
class Meta:
model = Question
fields = [
'id',
'label',
'order',
'answers'
]
def create(self, validated_data):
answers = validated_data.pop('answers', [])
question = super().create(validated_data)
for answer in answers:
answer['question'] = question.id
serializer = AnswerSerializer(data=answer)
serializer.is_valid(raise_exception=True)
serializer.save()
return question
class QuizSerializer(serializers.ModelSerializer):
questions = serializers.ListField(
child=serializers.DictField(), required=True)
class Meta:
model = Quiz
fields = ['id', 'name', 'questions_count', 'questions']
def create(self, validated_data):
questions = validated_data.pop('questions', [])
quiz = super().create(validated_data)
for question in questions:
question['quiz'] = quiz.id
serializer = QuestionSerializer(data=question)
serializer.is_valid(raise_exception=True)
serializer.save()
return quiz
Я хочу опубликовать данные запроса, например:
{
"name": "GK5",
"questions_count": 10,
"questions": [
{
"label": "World Tourism Day is celebrated on-5",
"order": 1,
"answers": [
{
"text": "September 5",
"is_correct": false
},
{
"text": "September 51",
"is_correct": false
},
{
"text": "September 52",
"is_correct": true
},
{
"text": "September 53",
"is_correct": false
}
]
}
]
}
Но это дает мне ошибку, когда я вызываю запрос на получение
Ошибка: для ключа, val в value.items () AttributeError: объект 'Question' не имеет атрибута 'items'
Как исправить?