Any way to find out if the _pre_put_hook file in ndb will save for the first time?

I want to run some things when creating the model, but not in updating the model. I could do this by adding a property, but I'm wondering if there is some kind of built-in functionality for targeting specifically for creating vs update.

+4
source share
2 answers

Any object that has been saved has a key, so checking this will tell you whether it is new or updated.

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

+6
source

You need to check for the identifier in the model key in _pre_put_hook.

If you look at the source for the ndb model class, you will see that the key was actually created and assigned to the model instance before calling _pre_put_hook, but the key does not have an identifier. This code inside _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' 
+4
source

Source: https://habr.com/ru/post/1481258/


All Articles