[英]Google App Engine: Datastore parent key confusion
I am currently learning more about the Google App Engine datastore, and I have some doubts regarding my understanding of the concept of defining a parent key. 我目前正在学习有关Google App Engine数据存储的更多信息,并且对我对定义父键的概念的理解有些疑问。 Now, here's the code for defining a parent key from the GAE documentation:
现在,这是GAE文档中定义父键的代码:
def guestbook_key(guestbook_name="default"):
"""Constructs a Datastore key for a Guestbook entity with guestbook_name."""
return ndb.Key('Guestbook', guestbook_name)
Note: this code is included in the source code of an application which accepts entries from a user and stores it in a datastore and displays them collectively on the homepage. 注意:此代码包含在应用程序的源代码中,该应用程序接受来自用户的条目并将其存储在数据存储区中,并在首页上集中显示它们。
Now, this is what I understand from this code(please correct me if my understanding of this concept is not what it is supposed to be): 现在,这就是我从这段代码中了解的内容(如果我对这个概念的理解不应该是这样,请更正我):
The 'guestbook_key' function defines a parent key, which we have named as 'default', for all the posts that the user submits into the datastore. “ guestbook_key”功能为用户提交到数据存储区的所有帖子定义一个父键,我们将其命名为“默认”。 So basically, all the posts that are submitted by the user are stored in an entity named 'Guestbook', and we define a key for it's parent(which is non-existent) named 'default'.
因此,基本上,用户提交的所有帖子都存储在名为“ Guestbook”的实体中,我们为其父(不存在)定义一个名为“ default”的键。
Please correct me wherever I went wrong with my understanding. 如果我的理解有误,请纠正我。
It really depends on how you use this key. 这实际上取决于您如何使用此密钥。 Right now, it is just a name.
现在,它只是一个名字。 If you
put()
it, you are putting a Guestbook
type with the name "default". 如果
put()
则将放置名称为“默认”的Guestbook
类型。
However, if you are using it as a parent, then you may have code that looks like this: 但是,如果您将其用作父级,则可能会有类似以下的代码:
post = Post(parent=guestbook_key())
post.comment = "This is a new post!"
post.put()
In this case, the new Post
object will have the Guestbook
object with the name "default" as a parent. 在这种情况下,新的
Post
对象将以名称为“ default”的Guestbook
对象作为父对象。 Then, you could use an ancestor query to get all Post
s for a given guestbook. 然后,您可以使用祖先查询来获取给定留言簿的所有
Post
。
The reason you might choose to do this (rather than, for example, have a property on each post with the name of the guestbook) is that it guarantees strongly consistent results. 您选择执行此操作的原因(而不是在每个帖子中都有一个带有留言簿名称的属性)是因为它保证了结果的高度一致 。 This basically allows all requests to see a consistent view of a guestbook.
基本上,这使所有请求都能看到留言簿的一致视图。 If you didn't have strongly consistent results, you may see cases where a user writes a post but when they look at the guestbook it doesn't appear.
如果结果不一致,您可能会看到用户写帖子的情况,但是当他们查看留言簿时却不会出现。
You are correct that you never actually need to create the Guestbook
entity. 没错,您实际上不需要创建
Guestbook
实体。 When you define a parent key, it is actually creating a key where the parent key is a prefix of the child key . 定义父键时,实际上是在创建一个键,其中父键是子键的前缀 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.