本文介绍了在App Engine中访问相关的对象键而不需要获取对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,对一个给定对象执行单个查询与许多查询比较好。假设我有一堆'儿子'物体,每个物体都有'父亲'。我得到了所有'儿子'对象:

  sons = Son.all()

然后,我想让那群儿子的所有父亲。我做:

  father_keys = {} 
在儿子的儿子中:
father_keys.setdefault(儿子。

然后我可以这样做:

 父亲= Father.get(father_keys.keys())

现在,假定son.father.key()实际上不会获取对象。我错了吗?我有一堆代码,假设object.related_object.key()实际上并没有从数据存储中获取related_object。



我是否正确地做了这件事?

解决方案

您可以通过研究下载App Engine SDK源代码 - 答案是,不,根据需要,没有特殊框架:<$在 ReferenceProperty 描述符中的c $ c> __ get __ 方法(用于1.3.0 SDK的源代码中的2887行) / em>知道是否 .key()或其他任何内容稍后会被调用到结果中,所以它只是没有机会执行您想要的优化。



然而,请参阅第2929行:method get_value_for_datastore strong>正是你想要的!



具体来说,不是 son.father.key(),使用 Son.father.get_value_for_datastore(son),你应该更加高兴作为结果; - )。


In general, it's better to do a single query vs. many queries for a given object. Let's say I have a bunch of 'son' objects each with a 'father'. I get all the 'son' objects:

sons = Son.all()

Then, I'd like to get all the fathers for that group of sons. I do:

father_keys = {}
for son in sons:
    father_keys.setdefault(son.father.key(), None)

Then I can do:

fathers = Father.get(father_keys.keys())

Now, this assumes that son.father.key() doesn't actually go fetch the object. Am I wrong on this? I have a bunch of code that assumes the object.related_object.key() doesn't actually fetch related_object from the datastore.

Am I doing this right?

解决方案

You can find the answer by studying the sources of appengine.ext.db in your download of the App Engine SDK sources -- and the answer is, no, there's no special-casing as you require: the __get__ method (line 2887 in the sources for the 1.3.0 SDK) of the ReferenceProperty descriptor gets invoked before knowing if .key() or anything else will later be invoked on the result, so it just doesn't get a chance to do the optimization you'd like.

However, see line 2929: method get_value_for_datastore does do exactly what you want!

Specifically, instead of son.father.key(), use Son.father.get_value_for_datastore(son) and you should be much happier as a result;-).

这篇关于在App Engine中访问相关的对象键而不需要获取对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 15:11