Reputation: 1057
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.
Upvotes: 4
Views: 3992
Reputation: 1867
based on Arakkal answer, however need to handle nested relations:
def changed_fields(instance, validated_data, changed_data=[]):
for field, value in validated_data.items():
if not isinstance(value, dict):
if value != getattr(instance, field, None):
changed_data.append(field)
else:
changed_fields(getattr(instance, field), validated_data[field], changed_data)
return changed_data
Upvotes: 0
Reputation: 88569
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)
Upvotes: 13