Josh.F
Josh.F

Reputation: 3806

Fetching entities from datastore where Entity.key.IN([keys...])

I'm trying to fetch a long list of entities, and those entities all refer to one of a few different related entities. It's explained in the comments, but basically many "items" reference to a few "Company"s. I don't want to have to make multiple queries for each key in unique_key (IE key.get()), so I thought the following would work but it's returning an empty list. Pray tell, what am I doing wrong? Or is there a better way to accomplish this relationship of many items referencing a few, while minimizing calls to the db (I'm new to AppEngine Datastore).

Notice, this is in Python, using the ndb library offered by app engine.

# "items" is a list of entities that have a property "parenty_company"
# parent_company is a string of the Company key
# I get a unique list of all Key strings and convert them to Keys
# I then query for where the Company Key is in my unique list

unique_keys = list(set([ndb.Key(Company, prop.parent_company) for prop in items]))
companies = Company.query(Company.key.IN(unique_keys)).fetch()

Upvotes: 0

Views: 106

Answers (1)

Dmytro Sadovnychyi
Dmytro Sadovnychyi

Reputation: 6201

You definitely should use ndb.get_multi(unique_keys). It will fetch all keys asynchronously in a single batch.

Upvotes: 1

Related Questions