pythongoogle-app-enginegoogle-cloud-datastoregqlquery

How can I filter by key, or keys, a query in Python for Google App Engine?


I have a query and I can apply filters on them without any problem. This works fine:

query.filter('foo =', 'bar')

But what if I want to filter my query by key or a list of keys?

I have them as Key() property or as a string and by trying something like this, it didn't work:

query.filter('key =', 'some_key')        #no success
query.filter('key IN', ['key1', 'key2']) #no success

Solution

  • Whilst it's possible to filter on key - see @dplouffe's answer - it's not a good idea. 'IN' clauses execute one query for each item in the clause, so you end up doing as many queries as there are keys, which is a particularly inefficient way to achieve your goal.

    Instead, use a batch fetch operation, as @Luke documents, then filter any elements you don't want out of the list in your code.