如何检查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
根据@NickJohnson的说法,调用count
这个函数会让你执行同样的查询两次。为了避免这种情况,而且因为你需要逐个查看评论,所以不如通过观察一个副作用来“检测”评论是否为空——也就是如果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"
0
Gql查询会给你一个查询对象,但不会直接给你结果(也就是数据实体)。要获取结果,你需要通过一些方法来提取这些结果,比如使用fetch、count、get,或者遍历结果集。