See Object changes in post_save in django rest framework

I am curious if there is a way to see what has changed on the object after saving it using the Django Rest Framework. I have some special behavior. I need to check if the field has been changed from its original value, which I was hoping to handle using post_saveon generics.RetrieveUpdateDestroyAPIView.

My first thought was to check with pre_save, but it seems that the object argument pre_savealready has the changes made to it.

+4
source share
2 answers

OLD ANSWER for django rest framework 2.3.12:

, - , , self.object, , serializer.object.

, pre_save, serializer.object, .

- self.object, self.get_object_or_none(). obj pre_save.

def pre_save(self,obj):
    unchanged_instance = self.object
    changed_instance = obj
    ..... # comparison code

django rest framework 3.3:

pre_save post_save http://www.django-rest-framework.org/topics/3.0-announcement/#generic-views

execute_update. :

def perform_update(self, serializer):
    # NOTE: serializer.instance gets updated after calling save
    # if you want to use the old_obj after saving the serializer you should
    # use self.get_object() to get the old instance. 
    # other wise serializer.instance would do fine
    old_obj = self.get_object()
    new_data_dict = serializer.validated_data
    # pre save logic
    if old_obj.name != new_data_dict['name']:
        do_something
    .....
    new_obj = serializer.save()
    # post save logic
    ......
+11

model_utils FieldTracker. , pre_save ( post_save ) :

def pre_save(self, obj):
    if hasattr(obj, 'tracker'):
        self.changed_fields = obj.tracker.changed()
    else:
        self.changed_fields = None

changed_fields : {'is_public': False, 'desc': None}

+1

All Articles