From 20e92c46a85aa535de92c145600094c601012eb0 Mon Sep 17 00:00:00 2001 From: Charles Connell Date: Fri, 25 Apr 2014 10:05:37 -0400 Subject: [PATCH] Reduce the number of database queries when loading the homepage --- karmaworld/apps/courses/models.py | 13 +++++++------ karmaworld/apps/courses/views.py | 3 +++ 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/karmaworld/apps/courses/models.py b/karmaworld/apps/courses/models.py index fdab324..de65a7a 100644 --- a/karmaworld/apps/courses/models.py +++ b/karmaworld/apps/courses/models.py @@ -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. """ diff --git a/karmaworld/apps/courses/views.py b/karmaworld/apps/courses/views.py index 082a7e4..ecdb9c7 100644 --- a/karmaworld/apps/courses/views.py +++ b/karmaworld/apps/courses/views.py @@ -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 -- 2.25.1