Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple models generic ListView to template

What is the SIMPLEST method for getting 2 models to be listed in a generic IndexView? My two models are CharacterSeries and CharacterUniverse.

My views.py

    from .models import CharacterSeries, CharacterUniverse


    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')


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

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

I need to know the shortest and most elegant code. Looked a lot but don't want to use mixins. I am perhaps not being pointed in the right direction.

Thanks all.

like image 434
Snerd Avatar asked Jun 30 '15 09:06

Snerd


2 Answers

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
like image 65
Snerd Avatar answered Sep 18 '22 17:09

Snerd


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')
like image 31
Pieter Hamman Avatar answered Sep 21 '22 17:09

Pieter Hamman