0

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.

Community
  • 1
  • 1
Simon Steinberger
  • 6,605
  • 5
  • 55
  • 97
  • IMO, `__init__` is not the best place to check to see if the object is being created/edited/deleted. But, if you absolutely need to do that, *new* objects do not have a `self.pk` if that is what you are looking for. In fact, the view might be a better place to figure out this logic instead of the model. – karthikr Oct 17 '14 at 21:51
  • I know about the "PK trick", but that doesn't help here. And yes, really, I know what I'm doing there. – Simon Steinberger Oct 17 '14 at 21:53
  • 1
    http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem – Ignacio Vazquez-Abrams Oct 17 '14 at 22:00
  • Okay, I've just added an explanation to what I'd like to do. – Simon Steinberger Oct 17 '14 at 22:19
  • 1
    It still doesn't make sense. Instantiating an object is completely separate from what might happen to it later. Where is the information stating "about to be deleted" supposed to be coming from? – Daniel Roseman Oct 17 '14 at 22:39
  • I meant 'deleted' is not a problem, because I don't need the old values for that. It's just the save method that I'd like to check for ... Is there a Python native way of finding out which class method is about to get called? – Simon Steinberger Oct 17 '14 at 22:42
  • @Daniel Roseman: I think that is actually the answer to my question - it's not possible inside the init method, as far as I could learn. If you post it, I'll accept it as correct. – Simon Steinberger Oct 31 '14 at 17:41

0 Answers0