Before you continue to read the post, i have to warn you that this is not the best way of getting the total count and there would be a possible inaccuracy and may not be scalable (http://groups.google.com/group/google-appengine/browse_thread/thread/3abb2868ab5fc304?pli=1), please use shared counter as what david suggested.
Here is a way on how to get the total count from a datastore in app engine, this uses memcache to cache the count for one minute (you can change this by passing an argument), i’m not sure but this seems to be better coz it doesn’t need you to do some writing on datastore.
from google.appengine.api import memcache
def get_total_count(self,model,cacheTime = 60,maxNumber = 10):
cacheName = model.kind() + “_totalCount”
total = memcache.get(cacheName)
if total == None:
index = 0
currentTotal = total = len(model.all().fetch(maxNumber,0 ))
while currentTotal == maxNumber:
index += 1
currentTotal = len(model.all().fetch(maxNumber,maxNumber * index))
total += currentTotal
memcache.add(cacheName, total, cacheTime)
return total
To call it on your get function:
self.response.out.write(str(get_total_count(self,<your model>))
or
self.response.out.write(str(get_total_count(self,<your model>,3600,1000))
* Remember that the maxNumber argument can only support upto 1000 and i encourage you to set it to 1000 if your datastore is big
Explanation to the codes:
cacheName = model.kind() + “_totalCount”
Create a variable and name it as our model’s name with an underscore totalCount (you can change this one)
total = memcache.get(cacheName)
if total == None:
index = 0
Change if there is already a cached value, if not set a index variable to 0 and ….
currentTotal = total = len(model.all().fetch(maxNumber,0 ))
Set the currentTotal and total variable to the len of a fetched row limit by maxNumber starting with the row 0
while currentTotal == maxNumber:
index += 1
currentTotal = len(model.all().fetch(maxNumber,maxNumber * index))
total += currentTotal
Loop until the currentTotal is not equal to the maxNumber and add the currentTotal to the total variable and add one to the index. Why do a while loop on currentTotal == maxNumber? Since we set a upper limit on the maximum number of rows we could fetch, it logically means that if we loop with the upper limit it would come to a point where it would never be equal to that limit.
memcache.add(cacheName, total, cacheTime)
Cache our total
Hope i’m right and it helps