【问题标题】:Google App Engine Datastore: creating and using a key without an entityGoogle App Engine Datastore:创建和使用没有实体的密钥
【发布时间】:2017-08-04 18:41:35
【问题描述】:

我有一个奇怪的问题想问所有 Google 数据存储专家。 我一直在研究一个有效的 Google App Engine 应用程序的代码。 我发现这几行代码让我很困惑。

guestbook_key = ndb.Key(Greeting, DEFAULT_GUESTBOOK_NAME)
mykey = ndb.Key(   Greeting, # kind 
                str(i+1), # id
                parent=guestbook_key # parent
                )
g = Greeting(key=mykey)`

我的问题是:作为父母,是否可以使用不存在的实体的键? 我这么说是因为没有创建具有键“guestbook_key”的实体(我在整个代码中搜索但我没有找到任何东西) 创建它只是为了给实体一个公共根而不创建实体根?

【问题讨论】:

  • 是的,文档明确表示您可以创建不引用实际实体的父键。

标签: google-app-engine google-cloud-datastore google-app-engine-python


【解决方案1】:

是的。来自Using the ancestor path in the key(强调我的):

ndb.Key('Account', 'sandy@example.com', 'Message', 123, 'Revision', '1')

...

在示例中,('Account', 'sandy@foo.com')('Message', 123)('Revision', '1') 都是种类标识符对的例子。

注意Message 不是模型类;它仅用作对修订进行分组的一种方式,而不是存储数据。

...

您可以使用命名参数 parent 来指定 直接上祖道。以下所有符号代表 相同的键:

ndb.Key('Account', 'sandy@example.com', 'Message', 123, 'Revision', '1')

ndb.Key('Revision', '1', parent=ndb.Key(
    'Account', 'sandy@example.com', 'Message', 123))

ndb.Key('Revision', '1', parent=ndb.Key(
    'Message', 123, parent=ndb.Key('Account', 'sandy@example.com')))

在上面引用的示例中,Message 实体键用作 Revision 实体的祖先/父键,但实际上不存在 Message 实体。

另一个这样的例子,这次显示了一个实际上并不存在的整个实体组的根(共同祖先):What would be the purpose of putting all datastore entities in a single group?

【讨论】:

    【解决方案2】:

    Key 只是程序内存中的一个对象,甚至在将任何内容写入数据存储之前。

    当您将实体写入数据存储区时,您需要提供密钥(完整,或者如果您需要自动 ID,则不完整)和数据本身。

    【讨论】:

      猜你喜欢
      • 2013-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多