【发布时间】:2014-07-09 22:00:19
【问题描述】:
views.py
class PaginatorView(_LanguageMixin, ListView):
context_object_name = 'concepts'
#some custom functions like _filter_by_first_letter
def get_queryset(self):
# some logic here ...
all_concepts = self._filter_by_letter(self.concepts, letters, startswith)
#letters and startswith are obtained from the logic above
print all_concepts
return all_concepts
def get_context_data(self, **kwargs):
context = super(PaginatorView, self).get_context_data(**kwargs)
print context[self.context_object_name]
context.update({
'letters': [(l[0], self._letter_exists(context[self.context_object_name], l)) for l in self.all_letters],
'letter': self.letter_index,
'get_params': self.request.GET.urlencode(),
})
return context
print all_concepts 语句正确打印了我的所有概念。所以直到这里的一切都很好。然后,我返回all_concepts。
此时不应该将all_concepts 添加到上下文中,在context_object_name 指定的键下吗?即,context['concepts'] 应该填充 all_concepts?
如果是这样,get_context_data 中的 print 语句不会打印任何内容。这表明我没有更新上下文。
当我之前使用 DetailView 时,get_object 函数正在正确更新 context_object_name 引用的上下文。(即 context[context_object_name] 填充了 get_object 返回的对象) get_queryset 不应该这样做ListView 也一样?
_LanguageMixin 也在 views.py 中定义,但与我的问题无关。只是把它放在这里给你看
class _LanguageMixin(object):
def dispatch(self, request, *args, **kwargs):
self.langcode = kwargs.pop("langcode")
self.language = get_object_or_404(Language, pk=self.langcode)
return super(_LanguageMixin, self).dispatch(request, *args, **kwargs)
def get_context_data(self, **kwargs):
context = super(_LanguageMixin, self).get_context_data(**kwargs)
context.update({"language": self.language,
"languages": Language.objects.values_list('code',
flat=True)})
return context
[EDIT1]
如果我保存all_concepts 即self.all_concepts=... 然后我使用self.all_concepts 而不是context[self.contex_object_name],一切正常。
[EDIT2]
我从不实例化 PaginatorView。它仅用于扩展目的。在这里你可以看到我是如何扩展它的。 self.concepts帮我在父类的get_queryset中找到all_concepts(PaginatorView)
class AlphabeticView(PaginatorView):
template_name = "alphabetic_listings.html"
model = Property
def get_queryset(self):
self.concepts = (
self.model.objects.filter(
name='prefLabel',
language__code=self.langcode,
)
.extra(select={'name': 'value',
'id': 'concept_id'},
order_by=['name'])
.values('id', 'name')
)
super(AlphabeticView, self).get_queryset()
【问题讨论】:
标签: django django-views django-class-based-views