Create and update 3 tables OneToMany relationship with nested serializers in Django Rest Framework

I have 3 tables in my database : Quiz - question - answer, with this models

class Quiz(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=255)


class Question(models.Model):
    id = models.AutoField(primary_key=True)
    question = models.CharField(max_length=255)
    quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE, related_name="questions")


class Answer(models.Model):
    id = models.AutoField(primary_key=True)
    answer = models.CharField(max_length=255)
    is_correct = models.BooleanField()
    question = models.ForeignKey(
        Question, on_delete=models.CASCADE, related_name="answers"
    )

i need to override create and update method for create or put/patch a quiz with questions and answers in one time with the default route.

i try différent things to do this. My create methode is is operational

thise is the serializers of quizz questio nand answers :

class AnswerSerializer(ModelSerializer):
    class Meta:
        model = Answer
        fields = (
            "id",
            "answer",
            "is_correct",
        )


class QuestionSerializer(ModelSerializer):
    answers = AnswerSerializer(many=True, required=True)

    class Meta:
        model = Question
        fields = ("id", "question", "answers")


class QuizSerializer(ModelSerializer):
    questions = QuestionSerializer(many=True, required=True)

    class Meta:
        model = Quiz
        fields = ("id", "name", "questions")

    # create function for create a quiz with questions and answers
    def create(self, validated_data: Dict[str, Any]) -> Quiz:
        questions = validated_data.pop("questions")
        quiz = Quiz.objects.create(**validated_data)
        for question in questions:
            answers = question.pop("answers")
            question = Question.objects.create(
                quiz=quiz, question=question.get("question")
            )
            for answer in answers:
                Answer.objects.create(
                    question=question,
                    answer=answer.get("answer"),
                    is_correct=answer.get("is_correct"),
                )
        return quiz

my views :

class AnswerViewSet(ModelViewSet):
    serializer_class = AnswerSerializer

    def get_queryset(self) -> Answer:
        return Answer.objects.all()


class QuestionViewSet(ModelViewSet):
    serializer_class = QuestionSerializer

    def get_queryset(self) -> Question:
        return Question.objects.all()


class QuizViewSet(ModelViewSet):
    serializer_class = QuizSerializer

    def get_queryset(self) -> Quiz:
        return Quiz.objects.all()

for the update this my last code with it i can update quiz table but not questions and answers

    def update(self, instance, validated_data):
        questions_data = validated_data.pop('questions')
        for question_data in questions_data:
            try:
                question = instance.questions.get(id=question_data.get('id'))
                answers_data = question_data.pop('answers')
                question_serializer = QuestionSerializer(question,data=question_data)
                question_serializer.is_valid(raise_exception=True)
                question_serializer.save()
                for answer_data in answers_data:
                    try:
                        answer = question.answers.get(id=answer_data.get('id'))
                        answer_serializer = AnswerSerializer(answer,data=answer_data)
                        answer_serializer.is_valid(raise_exception=True)
                        answer_serializer.save()
                    except Answer.DoesNotExist:
                        continue
            except Question.DoesNotExist:
                continue
        for attr, value in validated_data.items():
            setattr(instance, attr, value)
        instance.save()
        return instance

this is the json for update :

{
    "id": 6,
    "name": "Quiz photoshop intermediaire",
    "questions": [
        {
            "id": 1,
            "question": "comment est composé un fichier image photoshop",
            "quiz": 6,
            "answers": [
                {
                    "id": 1,
                    "answer": "de pizza 4 chaussures",
                    "is_correct": false,
                    "question": 1
                },
                {
                    "id": 2,
                    "answer": "d'un système de poulies",
                    "is_correct": false,
                    "question": 1
                },
                {
                    "id": 3,
                    "answer": "de calques",
                    "is_correct": true,
                    "question": 1
                }
            ]
        },
        {
            "id": 2,
            "question": "quelles sont les modes de couleurs indesign",
            "quiz": 6,
            "answers": [
                {
                    "id": 4,
                    "answer": "c'est un tquiz photoshop boulet !",
                    "is_correct": true,
                    "question": 2
                },
                {
                    "id": 5,
                    "answer": "CMJN",
                    "is_correct": true,
                    "question": 2
                },
                {
                    "id": 6,
                    "answer": "nono le petit robot",
                    "is_correct": false,
                    "question": 2
                },
                {
                    "id": 7,
                    "answer": "bombe de peinture",
                    "is_correct": false,
                    "question": 2
                }
            ]
        }
    ]
}

thanks for help :)

Back to Top