我的问题是,创建新模型实体的最佳方法是什么,然后立即阅读。例如,
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()
这通常会引发异常,例如:
AttributeError: 'NoneType' object has no attribute 'key'
即新LeftModel 实体的检索不成功。我在 appengine 中遇到过几次这个问题,而我的解决方案总是有点 hacky。通常我只是把所有东西都放在一个 try except 或一个 while 循环中,直到成功检索到实体。如何确保始终检索模型实体而不冒无限循环的风险(在 while 循环的情况下)或弄乱我的代码(在 try except 语句的情况下)?