gpt4 book ai didi

django - 覆盖 Django REST Frameworks 更新方法以保存嵌套的序列化程序

转载 作者:行者123 更新时间:2023-12-04 16:02:02 26 4
gpt4 key购买 nike

我是 DRF 的新手,我一直对如何覆盖 serializers.py 文件中的更新方法感到困惑。

这是我的模型。

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


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

为这些模型创建的序列化程序如下:-

class QuizSerializer(serializers.HyperlinkedModelSerializer):
questions = Quiz_QuestionSerializer(many=True)
class Meta:
model = Quiz
fields = ('url', 'quiz_name', 'module_referred')



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


def create(self, validated_data):
quiz_data = validated_data.pop('quiz')
module = Course_Module.objects.create(**validated_data)
for qd in quiz_data:
Quiz.objects.create(module_referred = module, **qd)
return module

def update(self, instance, validated_data):
# Somehow save instance with new quiz_data
return instance

上述模式的典型 JSON 表示如下:-

{
"url": "http://localhost:8080/api/registration_courses_modules/51/",
"name": "cdcsdc",
"quiz": [{
"url": "http://localhost:8080/api/registration_quiz/1/",
"quiz_name": "Shash",
"module_referred": "http://localhost:8080/api/registration_courses_modules/19/"
}]
}

我想要实现的是从 Course_ModuleSerialzers Update 方法中调用 QuizSerializer 的创建方法,然后将其作为属性绑定(bind)到 Course_modules 实例。

非常感谢任何帮助。谢谢。

最佳答案

模型.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")

序列化器.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

关于django - 覆盖 Django REST Frameworks 更新方法以保存嵌套的序列化程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50177697/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com