How can I create a new model object and then read it right after?

My question is what is the best way to create a new model object and then read it right after. For instance,

class LeftModel(ndb.Model):
    name = ndb.StringProperty(default = "John")
    date = ndb.DateTimeProperty(auto_now_add=True)

class RightModel(ndb.Model):
    left_model = ndb.KeyProperty(kind=LeftModel)
    interesting_fact = ndb.StringProperty(default = "Nothing")

def do_this(self):
    # Create a new model entity
    new_left = LeftModel()
    new_left.name = "George"
    new_left.put()

    # Retrieve the entity just created
    current_left = LeftModel.query().filter(LeftModel.name == "George").get()

    # Create a new entity which references the entity just created and retrieved
    new_right = RightModel()
    new_right.left_model = current_left.key
    new_right.interesting_fact = "Something"
    new_right.put()

This quite often raises an exception like:

AttributeError: 'NoneType' object has no attribute 'key'

those. A search for a new LeftModel object failed. I ran into this problem several times with appengine, and my solution was always a bit hacked. Usually I just put everything in a loop, except for a while or while loop, until the object is successfully retrieved. How can I guarantee that the model object is always fetched without the risk of endless loops (in the case of the while loop) or ruin my code (in the case of try except statements)?

+5
source share
1 answer

put().

new_left new_right, new_right.left_model = current_left.key

, , , HRD , , put . , , . , , , , . https://developers.google.com/appengine/docs/python/datastore/structuring_for_strong_consistency

, , , .

+9

All Articles