Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to tell if _pre_put_hook in ndb is saving for the first time?

I want to run some stuff on model creation, but not on model update. I could do this by adding a property, but I'm wondering if there's some kind of built in functionality for targeting specifically creation vs update.

like image 745
Joren Avatar asked Dec 20 '22 05:12

Joren


2 Answers

Any entity that has been stored has a key, so checking for that will tell you if it's new or being updated.

https://developers.google.com/appengine/docs/python/ndb/keyclass

like image 174
Brian Michelich Avatar answered May 16 '23 01:05

Brian Michelich


You need to check for the presence of an ID in the model key within the _pre_put_hook.

If you look at the source for the ndb Model class you can see that a key is actually created and assigned to the model instance before the _pre_put_hook is called, but the key has no ID. This code within the _pre_put_hook should work:

def _pre_put_hook(self):
    if self.key.id() is None:
        print 'model has not been saved'
    else:
        print 'model has been saved'
like image 23
PGower Avatar answered May 16 '23 00:05

PGower