1

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

2 回答 2

0

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

于 2013-02-27T12:55:46.217 回答
0

根据@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"
于 2013-02-27T13:00:51.787 回答