在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
答案 0 :(得分:0)
您可以使用setattr()
def update(self, instance, validated_data):
for key,value in validated_data.items():
setattr(instance,key,value)
instance.save()
return instance