【问题标题】:Get the string-encoded key of an entity from a reference property in appengine从 appengine 中的引用属性获取实体的字符串编码键
【发布时间】:2011-03-16 08:11:30
【问题描述】:

为了获取实体的字符串编码键,我只需执行以下操作:

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

如何在不获取父实体的情况下,通过子实体获取生物父的字符串编码键?

谢谢!

【问题讨论】:

  • 我认为我的回答会对您有所帮助.. 否则请尝试更具体

标签: google-app-engine referenceproperty


【解决方案1】:

您可以像这样获取引用属性的键,而无需获取它:

ChildClass.bio_parent.get_value_for_datastore(child_instance)

从那里,您可以像往常一样获取字符串编码形式。

【讨论】:

  • 我开始成为你的粉丝了。你能给我一些关于appengine的好书吗
  • @Abdul 这取决于你要找什么样的书。 Dan Sanderson 编写的 Google App Engine 编程很好。
【解决方案2】:

parent 是模型类中的关键字参数。所以,当你使用

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

它指的是该实体的 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

【讨论】:

  • 好的,我进行了相应的编辑。您对如何在不获取父类实体的情况下通过子类实体获取孩子的生物父母的字符串编码键有什么建议吗?
【解决方案3】:

我认为您可以通过这种方式实现。

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

【讨论】:

  • 我想获得字符串编码的密钥而不从数据存储中获取父类实体。您的答案首先从数据存储中获取。
  • 是的,您的解决方案有效,但不符合要求。正如我在问题中所说,我想在不从数据存储中获取父类实体的情况下获取它。您的解决方案获取了我想避免的父类。
  • 我认为不可能这样做。这样,您可以更改模型以使用 db.ListProperty(db.Key) 存储密钥。要了解有关建模的更多信息,您可以在这里查看Appengine Data modeling
猜你喜欢
  • 2010-10-21
  • 2017-12-07
  • 2023-03-16
  • 2020-09-29
  • 2021-09-22
  • 1970-01-01
  • 2011-05-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多