How can I check inside a Django model's init method, whether the object is about to get saved or deleted. I'd like to do some stuff only before the save or deleted method gets called.
class Book(models.Model):
title = models.CharField(max_length=150)
def __init__(self, *args, **kwargs):
super(Book, self).__init__(*args, **kwargs)
if self.is_about_to_get_saved_or_deleted:
do_something()
To say a few words about the why:
I need to implement live Elasticsearch search index updates. Therefore, I need to check whether certain model field values are changes or if an object gets deleted. Delete is not a problem. However, to see if field values have changed inside the save method, I need to store a heap of values inside the init method first:
https://stackoverflow.com/a/1793323/996638
But the init method also gets called when merely reading an object. In order to prevent the overhead, I'd like to store the relevant (old) field values only if the object is about to get saved. This would require only one IF statement as overhead.