如何在DRF序列化器中更新多个实例字段?

时间:2019-03-01 14:51:23

标签: django rest serialization django-models django-rest-framework

在DRF文档中:https://www.django-rest-framework.org/tutorial/1-serialization/#creating-a-serializer-class

显示了如何使用update方法更新现有实例。但是,显示的代码是高度重复的,并且如果更新模型,则会出现DRY问题。在调用validated_data之前如何将instance传递到save一次?

    def update(self, instance, validated_data):
        """
        Update and return an existing `Snippet` instance, given the validated data.
        """
        instance.title = validated_data.get('title', instance.title)
        instance.code = validated_data.get('code', instance.code)
        instance.linenos = validated_data.get('linenos', instance.linenos)
        instance.language = validated_data.get('language', instance.language)
        instance.style = validated_data.get('style', instance.style)
        instance.save()
        return instance

1 个答案:

答案 0 :(得分:0)

您可以使用setattr()

def update(self, instance, validated_data):
    for key,value in validated_data.items():
        setattr(instance,key,value)
    instance.save()
    return instance