Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest Framework serializer update method does not save object

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.

like image 929
darkhorse Avatar asked Jun 07 '26 03:06

darkhorse


1 Answers

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)  
like image 196
Rahul Gupta Avatar answered Jun 10 '26 02:06

Rahul Gupta