简体   繁体   English

查询ReferenceProperty

[英]Query on ReferenceProperty

Given that I have the following entities in the datastore: 鉴于我在数据存储区中有以下实体:

class Owner(db.Model):
  name = db.StringProperty()
  age = db.IntegerProperty()

class Pet(db.Model):
  name = db.StringProperty()
  owner = db.ReferenceProperty(Owner)

and that some owners have no pets, how best to extract all owners who have a pet, ordered by owner age? 并且有些业主没有宠物,如何最好地提取所有拥有宠物的业​​主,按业主年龄排序? I'm aware that JOINS are not possible, so it seems likely that there will be two queries. 我知道JOINS是不可能的,所以似乎有两个查询。

I have tried to extract all owner keys from Pets and then have done an 'IN' query with the keys but I hit the maximum 30 subqueries limitation. 我试图从Pets中提取所有所有者密钥,然后使用密钥完成了“IN”查询,但我达到了最多30个子查询限制。

I would add an additional property or two to the Owner class. 我会在Owner类中添加一两个属性。

Define a boolean field owns_pets (or similiar) which you set to True when you add a pet, then select all Owners where owns_pets == True , ordered by Age, then fetch the pets for each Owner using the reverse set. 定义一个布尔字段owns_pets (或类似),当您添加宠物时,将其设置为True,然后选择所有owns_pets == True Owners,按Age排序,然后使用反向集为每个所有者获取宠物。

Alternately add a ListProperty pets containing all the keys of the owned Pets. 或者添加一个ListProperty pets其中包含所有pets的所有钥匙。 Then query for all owners (again easier with the boolean above) and then db.get(some_owner.pets) 然后查询所有所有者(再次使用上面的布尔值更容易)然后db.get(some_owner.pets)

Without either of these you have a couple of less easy ways. 如果没有其中任何一种,你就会有一些不太简单的方法。

loop through the set of owners in Age order, fetch reverse reference set (in your case pet_set ) skipping owners where pet_set returns nothing. 循环遍历年龄顺序中的所有者集,获取反向引用集(在您的情况下为pet_set )跳过其中pet_set不返回任何内容的所有者。

Other ways include fetching all pets, collecting the keys of the owners (in a set, removing duplicates) and then db.get(list of owner keys), then order them after the fact in code - not as efficient if you have a lot or possibly not doable (memory/time).) If you want to use this path, have a look at nick johnson prefetch reference set code http://blog.notdot.net/2010/01/ReferenceProperty-prefetching-in-App-Engine 其他方法包括获取所有宠物,收集所有者的密钥(在一个集合中,删除重复项),然后db.get(所有者密钥列表),然后在代码中对它们进行排序 - 如果你有很多,那么效率不高或者可能不可行(内存/时间)。)如果要使用此路径,请查看nick johnson预取引用集代码http://blog.notdot.net/2010/01/ReferenceProperty-prefetching-in-App -发动机

Really the best bet is start storing redundant data at write time, that makes often used queries less expensive to perform. 真正最好的选择是在写入时开始存储冗余数据,这使得经常使用的查询执行成本更低。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM