Django classbasedview从get\u querys访问上下文数据

2024-09-29 17:17:32 发布

您现在位置:Python中文网/ 问答频道 /正文

class ProfileContextMixin(generic_base.ContextMixin, generic_view.View):

    def get_context_data(self, **kwargs):
        context = super(ProfileContextMixin, self).get_context_data(**kwargs)
        profile = get_object_or_404(Profile, user__username=self.request.user)
        context['profile'] = profile
        return context

class CourseListView(ProfileContextMixin, generic_view.ListView):
    model = Course
    template_name = 'course_list.html'
    object_list = None

    def get_queryset(self):
        profile = self.get_context_data()['profile']
        return super(CourseListView, self).get_queryset().filter(creator=profile)

我有以下两个基于类的视图。CourseListView继承了我编写的ProfileContextMixin,这样我就不必每次在其他视图中重复重写{}来获得{}。在

现在在我的CourseListView中,我需要根据creator参数过滤结果,这与在get_context_data中检索到的参数相同

我知道我的get_queryset起作用,它会调用get_context_data()来获取配置文件,但这也会导致我的get_context_data被调用两次,执行同一个SQL两次。在

有没有一种方法可以有效地访问上下文?在

更新:

在阅读了ListView方法流程图之后,我最终还是这样做了,但不确定这是否是最好的方法。感谢反馈。在

^{pr2}$

Tags: 方法selfviewdatagetdefcontextprofile
1条回答
网友
1楼 · 发布于 2024-09-29 17:17:32

您可以将gettingprofile从get_context_data移到上面的函数,比如dispatch,或者使用^{}修饰符。这样,您的概要文件将存储在视图的_profile参数中,并且在第二次调用self.profile之后,您将不会对DB执行第二次get。在

from django.utils.functional import cached_property

class ProfileContextMixin(generic_base.ContextMixin, generic_view.View):
    @cached_property
    def profile(self):
        return get_object_or_404(Profile, user__username=self.request.user)

    def get_context_data(self, **kwargs):
        context = super(ProfileContextMixin, self).get_context_data(**kwargs)
        context['profile'] = self.profile
        return context

class CourseListView(ProfileContextMixin, generic_view.ListView):
    model = Course
    template_name = 'course_list.html'
    object_list = None

    def get_queryset(self):
        return super(CourseListView, self).get_queryset().filter(creator=self.profile)

相关问题 更多 >

    热门问题