Home > Software engineering >  update in serializer: django rest framework
update in serializer: django rest framework

Time:10-29

I have a doubt, how to use update() in serializer?

serializers.py

 def update(self, instance, validated_data):
        instance.name = validated_data.get('name', instance.name)
        instance.description = validated_data.get('description', instance.description)
        instance.is_free = validated_data.get('is_free', instance.is_free)
        instance.keyarea = validated_data.get('keyarea', instance.keyarea)
        instance.subject = validated_data.get('subject', instance.subject)

        beneficiary_data = validated_data.get('beneficiary', instance.beneficiary)
        instance.beneficiary.set(*[beneficiary_data])

        section_data = validated_data.get('section', instance.section)
        instance.section.set(*[section_data])

        instance.image = validated_data.get('image', instance.image)
        instance.instructor = validated_data.get('instructor', instance.instructor)
        instance.relevance = validated_data.get('relevance', instance.relevance)
        instance.difficulty = validated_data.get('difficulty', instance.difficulty)
        instance.contributor = validated_data.get('contributor', instance.contributor)
        instance.general_status = validated_data.get('general_status', instance.general_status)
        instance.review_status = validated_data.get('review_status', instance.review_status)

        instance.save()
        return instance


I use a lot of lines here to update the course model, is there any other way to simplify this?

CodePudding user response:

It's OK generally, but you can do sth like this:

for k, v in validated_data.items():
    setattr(instance, k, v)
  • Related