Getting a list of children in App Engine using get_by_key_name (Python)

My adventures with entity groups continue after a slightly embarrassing start (see In some cases, calling App Engine get_by_key_name

using an existing key_name returns None
).

Now I see that I cannot make a normal call get_by_key_name

over a list of entities for child objects that have more than one parent. As the model docs say,

Multiple objects requested by the same ( get_by_key_name

) all must have the same parent.

I am used to doing something like the following:

# Model just has the basic properties
entities = Model.get_by_key_name(key_names)
# ContentModel has all the text and blob properties for Model
content_entities = ContentModel.get_by_key_name(content_key_names)

for entity, content_entity in zip(entities, content_entities):
 # do some stuff

      

Now that ContentModel objects are children of the model, this will not work due to the single parent requirement.

An easy way to include the above scenario with entity groups is to pass a parent list to the call get_by_key_name

, but I assume there is a good reason why this is not currently possible. I'm wondering if this is a hard-and-fast rule (since there is absolutely no way to invoke such a call), or perhaps the db module could be modified to make this type of invocation work, even if it meant higher CPU costs.

I would also love to see others accomplish this task. I can think of ways to handle it, for example using GQL queries, but none of them can think of call performance get_by_key_name

.

+2


source to share


2 answers


Just create a list of keys and do it.

entities = Model.get_by_key_name(key_names)
content_keys = [db.Key.from_path('Model', name, 'ContentModel', name) 
                for name in key_names]
content_entities = ContentModel.get(content_keys)

      



Note that I am assuming the key name for each ContentModel is the same as its parent model. (For a 1: 1 relationship, it makes sense to reuse key_name.)

+4


source


I am embarrassed to say that the restriction ('must be in the same group of persons') no longer applies in this case. Please feel free to file a bug in the documentation!



In any case, get_by_key_name is just syntactic sugar for getting, as Bill Katz illustrates. You can take it one step further and use db.get on the key list to get everything in one go - db.get doesn't care about the model type.

+1


source







All Articles