Python django.views.generic.base 模块,TemplateResponseMixin() 实例源码

我们从Python开源项目中,提取了以下1个代码示例,用于说明如何使用django.views.generic.base.TemplateResponseMixin()

项目:educa-coursware    作者:kkampardi    | 项目源码 | 文件源码
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,
                                        })