Skip to content Skip to sidebar Skip to footer

Is It Possible To Determine With Ndb If Model Is Persistent In The Datastore Or Not?

I am in process of migration from db.Model to ndb.Model. The only issue that I have to solve before finish this migration is that there is no Model.is_saved method. I have used db

Solution 1:

To get the same kind of state in NDB you would need a combination of post-get-hook and post-put-hook to set a flag. Here's a working example:

classEmployee(ndb.Model):
  <properties here>

  saved = False# class variable provides default value  @classmethoddef_post_get_hook(cls, key, future):
    obj = future.get_result()
    if obj isnotNone:
      # test needed because post_get_hook is called even if get() fails!
      obj.saved = Truedef_post_put_hook(self, future):
    self.saved = True

There's no need to check for the status of the future -- when either hook is called, the future always has a result. This is because the hook is actually a callback on the future. However there is a need to check if its result is None!

PS: Inside a transaction, the hooks get called as soon as the put() call returns; success or failure of the transaction doesn't enter affect them. See https://developers.google.com/appengine/docs/python/ndb/contextclass#Context_call_on_commit for a way to run a hook after a successful commit.

Solution 2:

Based on @Tim Hoffmans idea you can you a post hook like so:

classArticle(ndb.Model):
    title = ndb.StringProperty()

    is_saved = Falsedef_post_put_hook(self, f):
        if f.state == f.FINISHING:
            self.is_saved = Trueelse:
            self.is_saved = False


article = Article()
print article.is_saved ## False
article.put()
print article.is_saved ## True

I can't guarantee that it's persisted in the datastore. Didn't find anything about it on google :)

On a side not, looking to see if a ndb.Model instance has a key won't probably work since a new instance seems to get a Key before it's ever sent to the datastore. You can look at the source code to see what happens when you create an instance of the ndb.Model class.

Solution 3:

If you do not mention a key while creating an instance of the Model, you can use the following implementation of is_saved() to know if the object has been written to the datastore or not atleast once. (should be appropriate if you are migrating from google.appengine.ext.db to google.appengine.ext.ndb)

Using the example given by @fredrik,

classArticle(ndb.Model):
    title = ndb.StringProperty()
    
    defis_saved(self):
        if self.key:
            returnTruereturnFalse

P.S. - I do not know if this would work with google.cloud.ndb

Post a Comment for "Is It Possible To Determine With Ndb If Model Is Persistent In The Datastore Or Not?"