GQL中如何count

如你所知,GQL中的所有查询都是“select * from",那么在此基础上,在普通关系数据库中的count语法自然就成了低效的选出全部再count了,

上网看有没有好的解决方案,有人给出google code上的相关优化教程:http://code.google.com/appengine/articles/sharding_counters.html#related

或直接参考这种方法:

"""
You have to flip your thinking when working with a scalable datastore like GAE to do your calculations up front. In this case that means you need to keep counters for each baz and increment them whenever you add a new bar, instead of counting at the time of display.
"""
class CategoryCounter(db.Model):
    category = db.StringProperty()
    count = db.IntegerProperty(default=0)

 then when creating a Bar object, increment the counter
def createNewBar(category_name):
  bar = Bar(...,baz=category_name)

  counter = CategoryCounter.filter('category =',category_name).get()
  if not counter:
    counter = CategoryCounter(category=category_name)
  else:
    counter.count += 1
  bar.put()
  counter.put()

db.run_in_transaction(createNewBar,'asdf')

# now you have an easy way to get the count for any specific category
CategoryCounter.filter('category =',category_name).get().count
原文地址:https://www.cnblogs.com/walkerwang/p/2031219.html