I'm trying to reduce a SQL call to a MySQL database and I'm curious if 
Django tries to do some of what I'm doing or if my method makes sense. 
I'm making a ratings app to rate ideas (a 1 to 5 star type of thing).

In my template I want to list both the number of ratings and also the 
average rating.  So I've made those both methods of the idea model that 
I ented to call in my template.

I store the ratings so both calls don't run similar queries:

     cached_ratings = None

     # Methods related to ratings
     #
     def get_all_ratings(self):
         self.cached_ratings = 
Rating.objects.filter(content_type=self.get_content_type(), 
object_id=self.id)

     def get_num_ratings(self):
         if not self.cached_ratings:
             self.get_all_ratings()
         return len(self.cached_ratings)

     def get_average_rating(self):
         if not self.cached_ratings:
             self.get_all_ratings()
         sum = 0
         for rating in self.cached_ratings:
             sum += rating.rating
         return float(sum) / self.get_num_ratings()

Is this a reasonable thing to do?

I know SQL is optimized for SELECT COUNT(*) so if there were a template 
where I were showing the total count and not the average I'm generally 
curious what the difference in speed would be between doing a len() and 
just calling the count() on the QuerySet.

Thanks,
Rob

--~--~---------~--~----~------------~-------~--~----~
 You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to