2

I want to pull all the objects from my list of their keys. Is there a better way than how I'm doing it now?

list_of_objs = []
for obj_key in list_of_keys:
    this_obj = db.get(obj.key)
    list_of_objs.append(this_obj)

4 Answers 4

6

According to documentation db.get may accept list of keys and fetch them in a single batch, which will be much faster.

list_of_objects = db.get(list_of_keys)
1
  • 2
    Just to note here that if someone is using the ndb: list_of_entities = ndb.get_multi(list_of_keys)
    – Jimmy Kane
    Jun 2, 2014 at 18:19
-1

Not familiar with your specific application (specifically the db.get) but you may want to consider a list comprehension.

list_of_objs = [db.get(obj.key) for obj in list_of_keys]
-1
list_of_objs = [db.get(key) for key in list_of_keys]
-2

You could use the IN operator

query = db.Query()
list_of_objs = query.filter('__key__ IN', ','.join(list_of_keys))

this (or something similar) should do the job

According to the docs such queries are possible

5
  • gae-datastore is just like a dictionary afaik ... not an actual database... I think at least ... Jun 2, 2014 at 16:49
  • 1
    check out the docs here: developers.google.com/appengine/docs/python/datastore/… I think it should be possible
    – wastl
    Jun 2, 2014 at 16:50
  • in that case +1 ... as this is obviously preferred if the appengine thing supports it Jun 2, 2014 at 16:52
  • I think this will work for my particular case, but I'm pretty sure the IN query has a limit of 30.
    – user1961
    Jun 2, 2014 at 17:27
  • 1
    A query using IN with a list of length N is essentially the same as doing N separate queries with = and merging the results. i.e. not at all efficient
    – Greg
    Jun 2, 2014 at 18:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.