Whoops, in the second method there is a typo. count() should be len(): average_rating = float(sum(ratings)) / len(ratings)
On Thu, May 5, 2011 at 00:23, Robert Kluin <robert.kl...@gmail.com> wrote: > Hi Wilson, > You outlined the pattern to do this yourself. Fetch the entities > you want to average, add up the ratings, then divide by the number of > ratings. There are several ways to do this, in Python one very easy > to follow method might look like: > > # Get the ratings entities. > ratings_entities = Ratings.all().fetch(100) > > total_rating = 0.0 > ratings_count = 0 > for entity in ratings_entities: > total_rating += entity.rating > ratings_count += 1 > > average_rating = total_rating / ratings_count > > # Or, more concisely > ratings = [entity.rating for entity in ratings_entities] > average_rating = float(sum(ratings)) / count(ratings) > > > However, note that you should *not* do this on every request. Your > app will perform terribly. Instead you should come up with a way to > compute and store the computed average rating. You could do this when > someone adds a rating, or periodically update the average. you'll > have to decide which method makes the most sense for you. > > > > Robert > > > > > > > On Wed, May 4, 2011 at 02:52, Wilson Giese <giese.wil...@gmail.com> wrote: >> I'm pretty new to databases and googles app engine, and I'm having a >> hard time getting saved data and averaging it. So basically we have a >> comments and ratings system where they can type comments and add >> ratings, but I can't figure out how to get all the ratings, and >> average them. I just simply do not know how to do it. >> >> Is there any way I can pull saved data and average? >> >> So say "rating" is in database, and there were 5 ratings currently. >> How would I get all ratings, add them together, and divide by the >> number of ratings. Is this even possible? >> >> Sorry if this is confusing. >> >> - Thanks in advance >> >> -- >> You received this message because you are subscribed to the Google Groups >> "Google App Engine" group. >> To post to this group, send email to google-appengine@googlegroups.com. >> To unsubscribe from this group, send email to >> google-appengine+unsubscr...@googlegroups.com. >> For more options, visit this group at >> http://groups.google.com/group/google-appengine?hl=en. >> >> > -- You received this message because you are subscribed to the Google Groups "Google App Engine" group. To post to this group, send email to google-appengine@googlegroups.com. To unsubscribe from this group, send email to google-appengine+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/google-appengine?hl=en.