Django Rest Framework序列化程序更新方法不保存对象 [英] Django Rest Framework serializer update method does not save object
问题描述
在保存对象之前,我已经覆盖了我的一个序列化器的update方法,以调用模型的方法。像这样:
I have overridden the update method for one of my serializers to call a model's method before saving the object. Like so:
class MyModelSerializer(serializers.ModelSerializer):
class Meta:
model = MyModel
fields = [...]
def update(self, instance, validated_data):
instance.model_method()
instance.save()
return instance
在我看来,我正在使用 serializer.save保存序列化程序。 ()
,当然也可以使用 MyModelSerializer(instance,data = request.data)
进行设置。但是,我的实例未保存。仅删除update方法可以保存实例,但显然不会调用 model_method()
。如何解决此问题?谢谢您的帮助。
In my views, I am saving the serializer using serializer.save()
, and of course setting it using MyModelSerializer(instance, data=request.data)
. However, my instance is not being saved. Just removing the update method saves the instance, but does not call the model_method()
obviously. How can I fix this issue? Thanks for any help.
推荐答案
您需要调用 super()
调用 instance.model_method()
之后的方法,以便将数据保存在更新的实例上。
You need to call super()
method after instance.model_method()
is called so as to save the data on the updated instance.
上面提到的方法的问题是 validated_data
未被用于 save()
保留实例不变。
The problem with the approach mentioned above in the question is that validated_data
is not used anywhere to save()
which leaves the instance as is.
class MyModelSerializer(serializers.ModelSerializer):
class Meta:
model = MyModel
fields = [...]
def update(self, instance, validated_data):
instance.model_method() # call model method for instance level computation
# call super to now save modified instance along with the validated data
return super().update(instance, validated_data)
这篇关于Django Rest Framework序列化程序更新方法不保存对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!