如何检查GQL对象是否为空

时间:2013-02-27 12:51:35

标签: python google-app-engine gql

我正在尝试检查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"

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

According to @NickJohnson,调用count需要执行两次相同的查询。所以为了避免这种情况,并且由于你将不得不迭代注释,你也可以通过观察副作用“检测”注释是否为空 - 如果{icomments 1}}为空:

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"