到目前为止,这是我所读过的(只是样例):
- ndb documentation - movie database structure on SO - Parent Key issues 对我来说,关键类似乎很简单。当您创建一个ndb实体时,数据存储会自动为您创建一个键,通常采用key(Kind, id)的形式,其中id是为您创建的。
假设您有以下两个模型:
class Blah(ndb.Model):
last_name = ndb.StringProperty()
class Blah2(ndb.Model):
first_name = ndb.StringProperty()
blahkey = ndb.KeyProperty()
所以,只需使用键值并且您想要将Blah1设置为父级(或者有几个姓氏相同的家庭成员)。
lname = Blah(last_name = "Bonaparte")
l_key = lname.put() **OR**
l_key = lname.key.id() # spits out some long id
fname_key = l_key **OR**
fname_key = ndb.Key('Blah', lname.last_name) # which is more readable..
然后:
lname = Blah2( parent=fname_key, first_name = "Napoleon")
lname.put()
lname2 = Blah2( parent=fname_key, first_name = "Lucien")
lname2.put()
到目前为止还不错(我想)。现在来谈谈Blah2的KeyProperty。假设Blah1仍然保持不变。
lname3 = Blah2( first_name = "Louis", blahkey = fname_key)
lname3.put()
这是否正确?
如何查询各种内容
查询姓氏:
Blah.query() # all last names
Blah.query(last_name='Bonaparte') # That specific entity.
名字:
Blah2.query()
napol = Blah2.query(first_name = "Napoleon")
bonakey = napol.key.parent().get() # returns Bonaparte's key ??
bona = bonakey.get() # I think this might be redundant
这是我迷失的地方。如何使用键或键属性通过名字查找Bonaparte。我没有在此处添加它,也许应该,那就是关于父母、祖父母、曾祖父母的讨论,因为键跟踪先辈/父母。
如何以及为什么要使用KeyProperty而不是固有的key类。另外,想象一下你有3个传感器s1、s2、s3。每个传感器都有成千上万次的读数,但你想保持与s1相关的读数,这样你就可以绘制出今天s1的所有读数。你会使用哪一个?KeyProperty还是key类?如果已经在其他地方回答了这个问题,我很抱歉,但我没有看到关于选择哪种方法以及为什么/如何的清晰示例/指南。