Manas Chaturvedi
Manas Chaturvedi

Reputation: 5540

Google App Engine datastore: filter()

I'm trying to retrieve an entry from Google App Engine's datastore using the filter() method as follows:

result = Sender.all().filter("email =", email).filter("source_address =", source).filter("dest_address =", dest).filter("food_type =", food_type)

Then, if such an entry exists, I change the value of one of the columns in that entry. Otherwise, I'm displaying an error message.

        if result:
            for e in result:
                e.time_of_delivery = toj
                e.put()
                self.response.write("Time of delivery successfully rescheduled !")
        else:
            self.response.write("No such request.") 

However, even when an entry in the datastore doesn't exist based on the conditions imposed by the filter() methods that I have used, the No such request. message is never displayed. Instead, all I get is a blank page.

What exactly is wrong with my code? Why is the else part of my code never executed when an entry is not found in the datastore, i.e when result = None ?

Upvotes: 0

Views: 98

Answers (3)

Tim Hoffman
Tim Hoffman

Reputation: 12986

The query object will always resolve to true as per the answer earlier..

The query is not performed until you count, iterate, fetch or get on it's result set.

I would do something more like

   has_result = False
   for e in results:
       e.time_of_delivery = toj
       e.put()
       self.response.write("Time of delivery successfully rescheduled !")
       has_result = True
   if not has_result:
       self.response.write("No such request.") 

Upvotes: 2

sirfz
sirfz

Reputation: 4277

object.__nonzero__:

Called to implement truth value testing and the built-in operation bool(); should return False or True, or their integer equivalents 0 or 1. When this method is not defined, __len__() is called, if it is defined, and the object is considered true if its result is nonzero. If a class defines neither __len__() nor __nonzero__(), all its instances are considered true.

It seems that the gae Query does not implement either __nonzero__ or __len__ so a better way to check is:

if result.count(limit=1):  # retrieves only 1 record
    # results exist
else:
    # results don't exist

Upvotes: 1

Nick D
Nick D

Reputation: 71

What do the logs from the App Engine Development server say? Your request looks like an old-style datastore request, not an ndb one, so you may have the wrong syntax and the code is throwing an exception before any response is sent.

Upvotes: -1

Related Questions