Caching based on dynamic data

Many times you will want to cache something that is based on dynamic data. In these cases, you have to build dynamic keys that contain all information required to uniquely identify the cached data. Edit the views.py file of the courses application and modify the CourseListView view to make it look like this:

class CourseListView(TemplateResponseMixin, View):    model = Course    template_name = 'courses/course/list.html'    def get(self, request, subject=None):        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'))        if subject: subject = get_object_or_404(Subject, ...

Get Django 2 by Example now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.