Reputation: 1318
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"
Upvotes: 7
Views: 2492
Reputation: 348
@hwhite4 answer does what is expected. However, if you want to avoid that database lookup, you can do instead:
old_object = form.initial['name']
Where name
is the name of the field.
Upvotes: 4
Reputation: 715
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
Upvotes: 7