我可以在Django generic.ListView中有多个列表吗?

use*_*163 8 django django-views

作为一名Django初学者,我正在研究django docs提供的教程,网址是https://docs.djangoproject.com/en/1.5/intro/tutorial04/

在其中,他们演示了按发布日期使用查询列出的多个民意调查的列表.我是否可以添加另一个列表以便也可以在模板中使用.示例按日期显示最新轮询的列表,并在同一页面上按字母顺序显示另一个轮询.

class IndexView(generic.ListView):
    template_name = 'polls/index.html'
    context_object_name = 'latest_poll_list'

    def get_queryset(self):
        """Return the last five published polls."""
        return Poll.objects.order_by('-pub_date')[:5]
Run Code Online (Sandbox Code Playgroud)

Fra*_*les 13

当然,您只需要编写自己的'get_context_data'方法,该方法将检索这些值,然后它们将在视图中可用.就像是:

def get_context_data(self, *args, **kwargs):
    context = super(IndexView, self).get_context_data(*args, **kwargs)
    context['alphabetical_poll_list'] = Poll.objects.order_by('name')[:5]
    return context 
Run Code Online (Sandbox Code Playgroud)

有了这个,{{latest_poll_list}}和{{alphabetical_poll_list}}将在您的模板中提供.