關於 GAE ndb 的 key

今天做了一點小實驗,與其去讀落落長的文件,可能這樣比較快:

假設 A 是一個 ndb 的資料物件(某個 class 的實體),那麼 A.key  將會取得這個物件的 key,形式大概是:Key('News', 5092919069376512),前面是 class name,後面是 key id,我們姑且將此key 設定給變數 k,這個 k 可以做幾個操作:

1. k.get()  -->  取得資料物件本身
2. k.kind()  --> 取得資料物件的類別名稱(Class name)
3. k.id()  --> 取得資料物件的 key 的 id (回傳為 Long Integer)
4. k.parent()  -->  取得資料物件的父物件(如果本身就是根節點則回傳 None)

key 類別所有可執行的操作請參考:https://cloud.google.com/appengine/docs/python/ndb/keyclass#instance_methods_noaffect


如果要建立一個 Key 類別物件,首先要知道這個物件的(從 root 節點)路徑,用英文術語講的話是:its ancestor path and terminating with those of the entity itself.

簡言之,一個資料庫物件的根節點實體可以由它的 class name(kinds) 和 id(identifiers) 產生出的Key 物件所指定(取得),如果是子節點實體,則是由一連串的 class name 和 id 產生的 Key 物件所指定(取得),英文原文如下: The constructor method for class Key accepts such a sequence of kinds and identifiers and returns an object representing the key for the corresponding entity.

我做了以下實驗:

k1 = ndb.Key('News', 5092919069376512)

用白話文講就是:要抓一個 class name 為 News 且 key id 為 5092919069376512(其實id 亦可是字串, 長整數是其中一選擇)的物件的 key,產生出的 Key 實體 k1  則可以用來取得物件實體 -->  k1.get()  會回傳一個 News 物件(如果真的有對應 key id 的 News 物件的話)

留言

熱門文章