2013-02-27 59 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"