【问题标题】:How to check if GQL object is empty如何检查 GQL 对象是否为空
【发布时间】:2013-02-13 06:57:58
【问题描述】:

我正在尝试检查 GQL 对象是否为空(在使用 Python 的 Google App Engine 中),我应该怎么做? 我试过了,但没有用:

comments = db.GqlQuery("SELECT * "
                                "FROM Comment "
                                "where ANCESTOR IS :1 "
                                "order by date DESC", 
                                movie_data) 
        if comments:
            ratingsum = 0
            i=0
            for comment in comments:
                ratingsum=ratingsum + comment.rating
                i+=1
            average = ratingsum/i
        else:
            average = "no ratings"

【问题讨论】:

    标签: python google-app-engine gql


    【解决方案1】:

    Gql 查询为您提供查询对象,但不提供结果(实体)。要获取结果,您必须获取结果:使用 fetch、count、get 或迭代结果集。

    【讨论】:

      【解决方案2】:

      According to @NickJohnson,调用count 需要执行两次相同的查询。因此,为了避免这种情况,并且由于您将不得不遍历 cmets,您不妨通过观察副作用来“检测” cmets 何时为空——如果 comments 是,i 将为零空:

      comments = db.GqlQuery("SELECT * "
                                      "FROM Comment "
                                      "where ANCESTOR IS :1 "
                                      "order by date DESC", 
                                      movie_data) 
      ratingsum = 0
      i = 0
      for comment in comments:
          ratingsum += comment.rating
          i += 1
      if i:    
          average = ratingsum/i
      else:    
          average = "no ratings"
      

      【讨论】:

        猜你喜欢
        • 2013-10-11
        • 1970-01-01
        • 2019-06-09
        • 1970-01-01
        • 1970-01-01
        • 2017-05-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多