2013-12-15 71 views
2

如何從模型(datastore ndb.Model)中設置Model屬性的值?在應用引擎中自動設置屬性值模型類

class Note(ndb.Model): 
    content = ndb.StringProperty() 
    date = ndb.DateTimeProperty(auto_now_add=True) 
    depth = ndb.IntegerProperty() 

    def _calculate_depth(self): 
     self.depth = len(self.key.parent().pairs()) 

note = Note(parent=ndb.Key('Note', 'main', 'Todo', 'task1') , content='whatever') 
note.put() 

我正在尋找的是,當創建新的註釋運行calculate_depth方法,它集深度的物業

解決方案:)

class Note(ndb.Model): 
    content = ndb.StringProperty() 
    date = ndb.DateTimeProperty(auto_now_add=True) 
    depth = ndb.ComputedProperty(lambda self: len(self.key.parent().pairs())) 


note = Note(parent=ndb.Key('Note', 'main', 'Todo', 'task1') , content='whatever') 
note.put() 
+0

我一直在尋找的是ComputedProperty,感謝@Jimmy凱恩我得到了它 –

回答

0

對不起,previus值事情。

你所尋找的是後PUT hooks.

我看到你的功能_calculate_depth您使用實體鍵的值。然後,實體不僅需要被創建,而且還被寫入ndb中以鍵入一個密鑰。

如果你想這樣的事情發生「自動」,然後Model__post_put_hook是你所需要的

+1

得益於它完美地工作:) –

+0

@ KAL-Mazrouai比請檢查正確的答案,並歡迎使用stackoverflow。 –

+0

我認爲前面的答案也是有效的,對其他人來說,保持兩個解決方案 –