def get(self, request, subject=None):
"""
We retrieve all subjects, including the total number of courses for each of
them. We use the ORM's annotate() method with the Count() aggregation
function for doing so.
"""
"""
Caching content
First we try to get the all_students key from the cache using cache.
get() . This returns None if the given key is not found. If no key is found (not cached
yet, or cached but timed out) we perform the query to retrieve all Subject objects
and their number of courses, and we cache the result using cache.set() .
"""
subjects = cache.get('all_subjects')
if not subjects:
subjects = Subject.objects.annotate(
total_courses=Count('courses'))
cache.set('all_subjects', subjects)
all_courses = Course.objects.annotate(total_modules=Count('modules'))
""""
We retrieve all available courses, including the total number of modules
contained in each course.
3. If a subject slug URL parameter is given we retrieve the corresponding
subject object and we limit the query to the courses that belong to the
given subject.
"""
if subject:
subject = get_object_or_404(Subject, slug=subject)
key = 'subject_{}_courses'.format(subject.id)
courses = cache.get(key)
if not courses:
courses = all_courses.filter(subject=subject)
cache.set(key, courses)
else:
courses = cache.get('all_courses')
if not courses:
courses = all_courses
cache.set('all_courses', courses)
"""
We use the render_to_response() method provided by
TemplateResponseMixin to render the objects to a template
and return an HTTP response
"""
return self.render_to_response({
'subjects' : subjects,
'subject' : subject,
'courses' : courses,
})