Search code examples
djangopython-3.x

In ModelAdmin, how do I get the object's previous values when overriding `save_model()`


When overriding ModelAdmin.save_model(), I want to be able to run some calculations between the object's new values vs its old ones. Is there any way that I can get the "old object" with all its previous data before the change?

For example, if I have an Object with obj.name = "foo" that I update via the Django admin app to now be obj.name = "bar", upon saving the following code should print out accordingly:

from django.contrib import admin

class ObjectAdmin(admin.ModelAdmin):
     def save_model(self, request, obj, form, change):
          old_object = self.get_old_object()
          print(old_object.name)  # Should print out "foo"
          print(obj.name)         # Should print out "bar"

Solution

  • So you could get the object via a database lookup like this

    old_object = self.model.objects.get(id=obj.id)
    

    If you need to deal with the case where it doesn't exists you can do

    try:
        old_object = self.model.objects.get(id=obj.id)
    except self.model.DoesNotExist:
        ...
    

    Also self.model is just set to the your model class in the ModelAdmin so you could replace that with your model class