强制性博客示例设置; Authors有Posts
class Author(db.Model):
name = db.StringProperty()
class Post(db.Model):
author = db.ReferenceProperty()
article = db.TextProperty()
bob = Author(name='bob')
bob.put()
首先要记住的是,单个实体组(包括单个实体)上的常规 get/put/delete 将按预期工作:
post1 = Post(article='first article', author=bob)
post1.put()
fetched_post = Post.get(post1.key())
# fetched_post is latest post1
如果您开始跨多个实体组进行查询,您只会注意到不稳定。除非您指定了 parent 属性,否则您的所有实体都位于单独的实体组中。因此,如果在bob 创建帖子之后,他可以看到自己的帖子很重要,那么我们应该注意以下几点:
fetched_posts = Post.all().filter('author =', bob).fetch(x)
# fetched_posts _might_ contain latest post1
fetched_posts 可能包含来自bob 的最新post1,但可能不会。这是因为所有Posts 不在同一个实体组中。在 HR 中进行这样的查询时,您应该认为 “为我获取鲍勃的最新帖子”。
由于在我们的应用程序中作者可以在创建后立即在列表中看到他的帖子很重要,我们将使用parent 属性将它们绑定在一起,并使用ancestor 查询仅获取帖子来自该组:
post2 = Post(parent=person, article='second article', author=bob)
post2.put()
bobs_posts = Post.all().ancestor(bob.key()).filter('author =', bob).fetch(x)
现在我们知道post2 将出现在我们的bobs_posts 结果中。
如果我们查询的目的是获取 “可能是所有最新帖子 + 绝对是 bob 的最新帖子”,我们需要进行另一个查询。
other_posts = Post.all().fetch(x)
然后将结果other_posts和bobs_posts合并在一起,得到想要的结果。