我是DRF的新手,我一直坚持如何在serializers.py文件中覆盖update方法。
以下是我的模特。
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的create方法,然后将其作为属性绑定到Course_modules实例。
非常感谢任何帮助。谢谢。
答案 0 :(得分:0)
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