我的問題是,創建新模型實體的最佳方式是什麼,然後立即閱讀它。例如,如何創建一個新的模型實體,然後立即讀取它?
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幾次遇到過這個問題,而且我的解決方案一直很有點冒險。通常我只是將所有內容都放在try或while循環中,直到成功檢索到實體。我如何確保始終檢索模型實體,而不會發生無限循環(在while循環的情況下)或弄亂我的代碼(在try語句的情況下)?
只是在創建時爲LeftModel設置了一個鍵,而不是使用自動生成的鍵。 – 2012-07-21 09:30:31
+1陳述問題 – msw 2012-07-21 12:25:14