2011-03-16 49 views
3

實體的字符串編碼的關鍵爲了得到一個實體的字符串編碼的關鍵,我只是做到以下幾點:獲得從引用屬性中的AppEngine

key = entity.key() 
string_encoded_key = str(key) 

我有另一個參考實體通過ReferenceProperty。

class ParentClass(db.Model): 
name = db.StringProperty() 

class ChildClass(db.Model): 
name = db.StringProperty() 
bio_parent = db.ReferenceProperty(ParentClass) 


johnnys_parent = ParentClass(name="John").put() 
child = ChildClass(name="Johnny",bio_parent=johnnys_parent).put() 

#getting the string-encoded key of the parent through the child 
child = ChildClass.all().filter("name","Johnny").get() 
string_encoded_key = str(child.bio_parent) # <--- this doesn't give me the string-encoded key 

如何通過子實體獲取生物父母的字符串編碼密鑰而無需獲取父實體?

謝謝!

+0

我認爲我的答案會幫助你..其他嘗試更具體 – 2011-03-16 11:17:10

回答

4

你可以參考屬性的關鍵並不獲取這樣的:

ChildClass.bio_parent.get_value_for_datastore(child_instance) 

從那裏,你可以獲取編碼形式像往常一樣的字符串。

+0

我開始成爲你的粉絲。你能否給我提供一些好的書,用於appengine – 2011-03-17 05:00:34

+0

@Abdul這取決於你要找什麼樣的書。 Dan Sanderson編寫的Google App Engine編程非常好。 – 2011-03-17 17:14:19

1

parent是模型類中的關鍵字參數。所以,當你使用

child = Child (name='Johnny', parent=parent) 

它指的是實體的parent而不是屬性。你應該把屬性的名字從父變成更有意義,更不明確的東西。

class ParentClass (db.Model): 
    name = db.StringProperty() 

class ChildClass (db.Model): 
    name = db.StringProperty() 
    ref = db.ReferenceProperty (ParentClass) 

johns_parent = ParentClass (name='John Sr.').put() 
john = ChildClass (name='John Jr.', ref=johns_parent).put() 

# getting the string encoded key 
children = ChildClass.all().filter ('name', 'John Jr.').get() 
string_encoded_key = str (children.ref) 

實體的父代只能在創建時分配。它處於實體的全部關鍵路徑中,不能在該實體的整個生命週期中改變。

資源:

  1. Model Class
  2. Reference Property
  3. Entity Groups and Ancestor Path
+0

好的,我相應地編輯它。你有沒有關於如何通過childclass實體獲取孩子生物父母的字符串編碼密鑰而不提取父類實體的建議? – Albert 2011-03-16 10:35:29

0

我認爲你可以做到這一點的方式。

string_encoded_key = str(child.bio_parent.key()) 
+0

我想獲取字符串編碼密鑰*,而不從數據存儲中獲取父類實體。您的答案首先從數據存儲中獲取。 – Albert 2011-03-16 10:34:11

+1

是的,您的解決方案有效,但不符合要求。正如我在我的問題中所述,我想在不從數據存儲中獲取父類實體的情況下獲取它。您的解決方案會提取我想要避免的父類。 – Albert 2011-03-16 11:55:23

+0

我認爲這是不可能的。通過這種方式,您可以使用db.ListProperty(db.Key)更改模型以存儲密鑰。要了解更多關於建模的信息,請點擊這裏[Appengine Data modeling](http://daily.profeth.de/2008/04/er-modeling-with-google-app-engine.html) – 2011-03-16 12:26:28