What's the best way to count results in GQL?

后端 未结 9 1552
情深已故
情深已故 2020-12-02 14:21

I figure one way to do a count is like this:

foo = db.GqlQuery(\"SELECT * FROM bar WHERE baz = \'baz\')
my_count = foo.count()

What I don\'

9条回答
  •  执念已碎
    2020-12-02 15:05

    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
    

提交回复
热议问题