Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get changed_fields in Django REST Framework Serializers during update?

Is there any way that I can get the 'changed_fields' before updating the model using ModelSerializer?

I want functionality like:

class MySerializer(serializers.ModelSerializer):
   class Meta:
      fields = '__all__'
      model = MyModel

  def update(self, validated_data):
      // Access old values and new values of model so that I can compare them.
      super(MySerializer, self).update(validated_data)

I don't want to query the database to fetch the old_values, because we've over millions of rows and it will take time to fetch that.

like image 784
Charanjit Singh Avatar asked Oct 31 '25 22:10

Charanjit Singh


1 Answers

The update() method takes two parameters instance and validated_data. The instance is the model instance that going to be updated and the validated_data is a dict that contain the data to be updated

class MySerializer(serializers.ModelSerializer):
    class Meta:
        fields = '__all__'
        model = MyModel

    def update(self, instance, validated_data):
        for field, value in validated_data.items():
            new_value = value
            old_value = getattr(instance, field)

        return super(MySerializer, self).update(instance, validated_data)
like image 141
JPG Avatar answered Nov 02 '25 13:11

JPG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!