2012-07-21 61 views
5

我的問題是,創建新模型實體的最佳方式是什麼,然後立即閱讀它。例如,如何創建一個新的模型實體,然後立即讀取它?

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語句的情況下)?

+1

只是在創建時爲LeftModel設置了一個鍵,而不是使用自動生成的鍵。 – 2012-07-21 09:30:31

+1

+1陳述問題 – msw 2012-07-21 12:25:14

回答

9

爲什麼試圖在執行put()後立即通過查詢獲取對象。

您應該使用new_left剛剛創建,並立即將其分配給new_right作爲new_right.left_model = current_left.key

無法查詢的原因馬上是因爲人力資源開發使用的最終一致性模型,這意味着你得到賣出期權將可見最終結果。如果你想要一個一致的結果,那麼你必須執行祖先查詢,這意味着創建關鍵的祖先。鑑於你正在創建一棵樹,這可能是不實際的。閱讀關於爲強一致性構造數據https://developers.google.com/appengine/docs/python/datastore/structuring_for_strong_consistency

我沒有看到任何原因,您只是不使用剛剛創建的實體而沒有附加查詢。

+0

+1要放大:「我該如何立即閱讀?」你不能,那不是NDB的設計目標,並且有很好的理由,它不能馬上得到。 – msw 2012-07-21 12:00:26

+7

澄清:該原因與NDB無關 - 這些HRD查詢語義在後端實現。 NDB只是傳遞壞消息。 (至於OP爲什麼試圖這樣做:我的猜測和任何一樣好,但我希望這個例子與發生這種事情的真實代碼相比簡化了,並且/或者他們正在編寫某種測試;也許他們也許正在將SQL成語翻譯成App Engine。) – 2012-07-21 20:17:53

相關問題