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
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.
You need to call super() method after instance.model_method() is called so as to save the data on the updated instance.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With