Google App Engine数据存储区:filter()

问题描述 投票:0回答:3

我正在尝试使用filter()方法从Google App Engine的数据存储区检索条目,如下所示:

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

然后,如果存在这样的条目,则更改该条目中列之一的值。 否则,我将显示一条错误消息。

        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.") 

但是,即使根据我使用的filter()方法施加的条件,即使数据存储区中的条目不存在,也不会No such request. 消息永远不会显示。 相反,我得到的只是一个空白页。

我的代码到底有什么问题? 当在数据存储区中找不到条目时,即result = None时,为什么我的代码的else部分从不执行?

python google-app-engine google-cloud-datastore
3个回答
2
投票

查询对象将始终按照前面的答案解析为true。

直到您对它的结果集进行计数,迭代,获取或获取后,查询才会执行。

我会做更多类似的事情

   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.") 

1
投票

object.__nonzero__

调用以实现真值测试和内置操作bool() ; 应该返回False或True,或者它们的等效整数0或1。如果未定义此方法,则调用__len__() (如果已定义),并且如果其结果为非零,则将该对象视为true。 如果一个类__len__()__nonzero__() ,则其所有实例均被视为true。

看来gae Query没有实现__nonzero____len__所以一种更好的检查方法是:

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

-1
投票

App Engine开发服务器的日志怎么说? 您的请求看起来像一个老式的数据存储请求,而不是ndb请求,因此您可能使用了错误的语法,并且代码在发送任何响应之前引发了异常。

© www.soinside.com 2019 - 2024. All rights reserved.