Reduce the number of database queries when loading the homepage
authorCharles Connell <charles@connells.org>
Fri, 25 Apr 2014 14:05:37 +0000 (10:05 -0400)
committerCharles Connell <charles@connells.org>
Fri, 25 Apr 2014 14:05:37 +0000 (10:05 -0400)
karmaworld/apps/courses/models.py
karmaworld/apps/courses/views.py

index fdab3242ca8329bbf809397578edf088154c70b8..de65a7aee1dc315df44d24b5bc5bc7e04ea83085 100644 (file)
@@ -312,12 +312,13 @@ class Course(models.Model):
 
     def get_popularity(self):
         """ Aggregate popularity of notes contained within. """
-        # Run an efficient GROUP BY aggregation within the database.
-        # It returns {'fieldname': #}, where fieldname is set in the left hand
-        # side of the aggregate kwarg. Call the field x and retrieve the dict
-        # value using that key.
-        # The value might be None, return zero in that case with shortcut logic.
-        return self.note_set.aggregate(x=models.Sum('thanks'))['x'] or 0
+        # This is optimized for the case where note_set has already been
+        # loaded into memory. In that case, we avoid making any more database
+        # queries.
+        sum = 0
+        for note in self.note_set:
+            sum += note.thanks
+        return sum
 
     def get_prof_names(self):
         """ Comma separated list of professor names. """
index 082a7e41f67de89fd4d81dcb5743e2b83abe6da1..ecdb9c78d4332045241d9c550abb954c10ef9001 100644 (file)
@@ -60,6 +60,9 @@ class CourseListSubView(ListView):
     """ Lists all courses. Called by CourseListView. """
     model = Course
 
+    def get_queryset(self):
+        return Course.objects.all().select_related('note_set', 'school', 'department', 'department__school')
+
     def get_context_data(self, **kwargs):
         """ Add the CourseForm to ListView context """
         # get the original context