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
方法流程图之后,我最终还是这样做了,但不确定这是否是最好的方法。感谢反馈。在
您可以将gettingprofile从} 修饰符。这样,您的概要文件将存储在视图的
get_context_data
移到上面的函数,比如dispatch
,或者使用^{_profile
参数中,并且在第二次调用self.profile
之后,您将不会对DB执行第二次get
。在相关问题 更多 >
编程相关推荐