benasio
benasio

Reputation: 529

Datastore Query filtering on list

Select all records, ID which is not in the list

How to make like :

query = Story.all()

query.filter('ID **NOT IN** =', [100,200,..,..])

Upvotes: 6

Views: 3012

Answers (3)

User 1058612
User 1058612

Reputation: 3819

This is an old question, so I'm not sure if the ID is a non-key property. But in order to answer this:

query = Story.all()
query.filter('ID **NOT IN** =', [100,200,..,..])

...With ndb models, you can definitely query for items that are in a list. For example, see the docs here for IN and !=. Here's how to filter as the OP requested:

query = Story.filter(Story.id.IN([100,200,..,..])

We can even query for items that in a list of repeated keys:

def all(user_id):
    # See if my user_id is associated with any Group.
    groups_belonged_to = Group.query().filter(user_id == Group.members)
    print [group.to_dict() for group in belong_to]

Some caveats:

There's docs out there that mention that in order to perform these types of queries, Datastore performs multiple queries behind the scenes, which (1) might take a while to execute, (2) take longer if you searching in repeated properties, and (3) will up your costs with more operations.

Upvotes: 0

Soe Thiha
Soe Thiha

Reputation: 41

This is now supported via GQL query

The 'IN' and '!=' operators in the Python runtime are actually implemented in the SDK and translate to multiple queries 'under the hood'.

For example, the query "SELECT * FROM People WHERE name IN ('Bob', 'Jane')" gets translated into two queries, equivalent to running "SELECT * FROM People WHERE name = 'Bob'" and "SELECT * FROM People WHERE name = 'Jane'" and merging the results. Combining multiple disjunctions multiplies the number of queries needed, so the query "SELECT * FROM People WHERE name IN ('Bob', 'Jane') AND age != 25" generates a total of four queries, for each of the possible conditions (age less than or greater than 25, and name is 'Bob' or 'Jane'), then merges them together into a single result set.

source: appengine blog

Upvotes: 2

Nick Johnson
Nick Johnson

Reputation: 101149

There's no way to do this efficiently in App Engine. You should simply select everything without that filter, and filter out any matching entities in your code.

Upvotes: 3

Related Questions