Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In django rest framework 3.0+, how to check object differences on update?

How can you check on save if the object was changed by the user? I.e. if any differences from the original database object were introduced. Before it was possible with pre_save() (See object changes in post_save in django rest framework), but now that was replaced with perform_update, which no longer holds both objects (original and modified) for comparison.

like image 707
calina-c Avatar asked Dec 16 '14 15:12

calina-c


1 Answers

In Django REST Framework 3, pre_save was replaced with perform_update, which only takes the serializer as an argument (instead of the object itself).

You can access the validated data that was passed into the request using the .validated_data attribute on the serializer. This is the recommended replacement for .object, and should allow you to determine what the differences are.

def perform_update(self, serializer):
    original_object = self.get_object() # or (the private attribute) serializer.instance
    changes = serializer.validated_data

    serializer.save(attr=changed_value) # pass arguments into `save` to override changes
like image 181
Kevin Brown-Silva Avatar answered Nov 15 '22 03:11

Kevin Brown-Silva