[Django]-Overriding Django REST Frameworks update method to save the nested serializers

4👍

models.py

class CourseModule(models.Model):
    name = models.CharField(max_length=200)

class Quiz(models.Model):
    quiz_name = models.CharField(max_length=200)
    module_referred = models.ForeignKey(CourseModule, related_name="quiz_set")

serializer.py

class CourseModuleSerializer(serializers.HyperlinkedModelSerializer):
    quiz = QuizSerializer(many=True, required=False)
    class Meta:
        model = CourseModule
        fields = ('url', 'name', 'quiz')


    def create(self, validated_data):
        quiz_data = validated_data.pop('quiz', [])
        course_module = CourseModule.objects.create(**validated_data)
        if quiz_data:
            Quiz.objects.bulk_create(
              [
                 Quiz(module_referred=course_module, **quiz)
                 for quiz in quiz_data
              ],
            )
        return course_module

    def update(self, instance, validated_data):
        instance.name = validated_data.get('name', instance.name)

        quiz_data = validated_data.get('quiz')
        if quiz_data:
            instance.quiz_set.clear()
            Quiz.objects.bulk_create(
               [
                 Quiz(module_referred=instance, **quiz)
                 for quiz in quiz_data
               ],
            )
        instance.save()
        return instance 

Leave a comment