views:

119

answers:

2

I like to check if there is any result for my datastore query in the Google App Engine Datastore. This is my query:

users = User.all()
users.filter("hash =", current_user_hash)

What is the fastest and most elegant way to check if my query returns any result?

PS: I know a way to do so, but I'm very unsure if it is very efficient...

+2  A: 

users.count(1) is probably the fastest way to do this; users.fetch(1) would be the other way to accomplish this, but requires fetching an entire entity; depending on the size of that entity this could be fairly slow.

Wooble
+4  A: 

If you also need to fetch the results, the most efficient way is to fetch the results with .fetch(), and then check if the list is nonempty. If you don't actually need the results, call .count(1).

What you shouldn't do is call .count(1) if you also need the results - this'll require executing the query twice.

Nick Johnson
Is there a significant difference in performance between doing a keys_only get and count(1)?
wings
count(1) is essentially a keys-only query that doesn't need to even return the keys - it's slightly more efficient, though not much.
Nick Johnson