Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google app engine How to count SUM from datestore?

Im wondering, how can i get a SUM of a rating entity i get from the datastore (python)?

should i:

ratingsum = 0
for rating in ratings:
    ratingsum + rating

print ratingsum

?

like image 573
Alon Avatar asked Apr 21 '10 20:04

Alon


1 Answers

Yep, that's pretty much it. Retrieve all the entities you want to sum, and sum them in your app. There is no SUM in GQL.

If what you're trying to accomplish is to find the average rating for an entity, there's a better way.

class RateableThing(db.Model):
    num_ratings = db.IntegerProperty()
    avg_rating = db.FloatProperty()

Finding the thing's average rating is a simple lookup, and adding a new rating is just:

thing.avg_ratings = ((thing.avg_ratings * thing.num_ratings) + new_rating) / thing.num_ratings + 1
thing.num_ratings += 1
thing.put()

The prevailing idiom of the App Engine datastore is to do as much work as you can on write, and as little as possible on read, since reads will happen much more often.

like image 135
Jason Hall Avatar answered Nov 04 '22 00:11

Jason Hall