2013-02-27 83 views
1

我想检查是否有GQL对象是否为空(在使用Python谷歌应用程序引擎),我应该怎么办呢? 我试过,但没有奏效:如何检查是否GQL对象为空

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" 

回答

0

的GQL查询为您提供了一个查询对象,而不是结果(实体)。要获得结果,您必须获取结果:使用fetch,count,get或遍历结果集。

0

According to @NickJohnson,呼吁count将需要执行相同的查询两次。因此,为了避免这种情况,因为你将不得不通过评论进行迭代,你还不如“检测”当评论是空的,通过观察副作用 - 这i将是零,如果comments为空:

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"