如何检查GQL对象是否为空

2024-10-03 17:21:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图检查一个GQL对象是否为空(在使用Python的googleappengine中),我应该怎么做? 我试过了,但没用:

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"

Tags: 对象fromdbiscommentwhereselectcomments
2条回答

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

According to @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"

相关问题 更多 >