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. """
""" 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