I’m using the webapp framework on GAE, and to show the results of a query, I’m doing a get() on the query object, then iterating on it if get() returned anything, for example:
query = Employee.all().filter("some_boolean_property = ", True)
if query.get():
for employee in query:
# output employee.name etc.
# ...
else:
# output "no records found" message
# ...
The reason I’m doing the get() and not just doing an else on the for loop is because I’m outputting the data in a table, and I don’t want to write the table code if there are no results. Previously instead of the get() I was doing fetch(1), but I believe they are equivalent (i.e, get() just executes the query but with a maximum of one result). Therein lies my question – is this true that I can use get() in this way, and is this the best way to do find out if a query returns results or not? Might count(1) be better?
I’m not concerned with the number of results, just if there are any or not.
An alternative might be to set a flag inside the loop to say that at least one record is found, then test that flag for your “no records found” case.
This has the advantage of removing a call to the datastore.