2

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.

4
  • What does the model_method do? Does it modify any attributes of the instance? Commented Nov 9, 2019 at 6:32
  • Yes, thats exactly what it does Commented Nov 9, 2019 at 10:23
  • Did you try returning super() call at the end ie after 1st line instead of calling instance.save(). Commented Nov 9, 2019 at 15:50
  • Could you write that out as an answer? Commented Nov 9, 2019 at 22:11

1 Answer 1

10

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)  
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.