获得从引用属性中的AppEngine

问题描述:

实体的字符串编码的关键为了得到一个实体的字符串编码的关键,我只是做到以下几点:获得从引用属性中的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

你可以参考属性的关键并不获取这样的:

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

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

我认为你可以做到这一点的方式。

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