在google app engine中,假设我有一个父实体和一个子实体:
class Parent(ndb.Model):
pass
class Child(ndb.Model):
parent_key = ndb.KeyProperty(indexed = True)
... other properties I don't need to fetch ...我有一个父母的密钥列表,比如parents_list,我正在试图有效地回答:在parents_list中,哪个父母有孩子。
理想情况下,我应该运行以下查询:
children_list = Child.query().filter(Child.parent_key = parents_list).fetch(projection = 'parent_key')由于相等筛选器中存在projection属性(parent_key),因此它不起作用。因此,我必须检索所有属性,这似乎效率很低。
有没有办法有效地解决这个问题?
发布于 2021-08-27 16:30:43
您的子模型实际上应该是
class Child(ndb.Model):
parent_key = ndb.KeyProperty(kind="Parent", indexed = True)如果您在Python2中执行此操作,则可以使用ndb_tasklet (请参阅下面的代码;请注意,我没有亲自执行此代码,因此不能保证它能正常工作;它只是用作指南,但我以前曾使用过微线程)。如果为python3,则尝试创建异步查询
class Parent(ndb.Model):
@classmethod
def parentsWithChildren(cls, parents_list):
@ndb.tasklet
def child_callback(parent_key):
q = Child.query(Child.parent_key == parent_key)
output = yield q.fetch_async(projection = 'parent_key')
raise ndb.Return ((parentKey, output))
# For each key in parents_list, invoke the callback - child_callback which returns a result only if the parent_key matches
# ndb.tasklet is asynchronous so code is run in parallel
final_output = [ child_callback(a) for a in parents_list]
return final_outputhttps://stackoverflow.com/questions/68953582
复制相似问题