Multiple models generic ListView to template

巧了我就是萌 提交于 2019-12-03 08:30:34

You can pass the one queryset in as context on the ListView like this,

class IndexView(generic.ListView):
    template_name = 'character/index.html'
    context_object_name = 'character_series_list'
    model = CharacterSeries

    def get_context_data(self, **kwargs):
        context = super(IndexView, self).get_context_data(**kwargs)
        context.update({
            'character_universe_list': CharacterUniverse.objects.order_by('name'),
            'more_context': Model.objects.all(),
        })
        return context

    def get_queryset(self):
        return CharacterSeries.objects.order_by('name')

https://docs.djangoproject.com/en/1.8/ref/class-based-views/mixins-simple/#django.views.generic.base.ContextMixin.get_context_data

Sounds like a mixin is the only (right)? way. I added a get_context_data method and now it works.

Quick question how about adding more than 2 models..?

below works with the 2 models now:

class IndexView(generic.ListView):
    template_name = 'character/index.html'
    context_object_name = 'character_series_list'

    def get_queryset(self):
        return CharacterSeries.objects.order_by('name')

    def get_context_data(self, **kwargs):
        context = super(IndexView, self).get_context_data(**kwargs)
        context['character_universe_list'] = CharacterUniverse.objects.order_by('name')
        return context
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!