Accessing a linked object without using an object in App Engine

In general, it is best to make one request against many requests 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 would like to get all the fathers for this group of sons. I:

 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 () does not actually fetch the object. Am I really wrong? I have a bunch of code that assumes that object.related_object.key () does not actually retrieve the associated_object from the data store.

Am I doing it right?

+7
python google-app-engine google-cloud-datastore
source share
2 answers

You can find the answer by looking at the sources of appengine.ext.db when loading the App Engine SDK sources - and Answer: no, there is no special case that you need: the __get__ method (line 2887 in the sources for SDK 1.3.0) of the ReferenceProperty descriptor starts before than finding out if .key() or something else will later be called on the result, so it just won’t get the opportunity to do the optimization you need.

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

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

+10
source share

I would rather scroll the sons and get the parent keys using son.parent_key() .

parent_key ()

Returns the key of the parent of this instance or None if this instance does not have a parent.

Since the entire path is stored in the instance key , there is theoretically no need to delete the database again to get the parent key.

After that, you can immediately get copies of all parents db.get () .

get (keys)

Gets the entity or entities for a given key or keys of any model.

Arguments:

keys Object Key or a list of Key objects .

If one key is provided, the return value is an instance of the corresponding model class, or None, if no entity exists with the given key. If the list of keys, return value - the corresponding list of models instances, with values ​​None, when no entity exists for the corresponding key.

+1
source share

All Articles