Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django how to get multiple context_object_name for multiple queryset from single view to single template

Tags:

python

django

I want to run multiple queryset from single view. I have done for single get_queryset and single context_object_name to pass into index.html template :

class IndexView(generic.ListView):
    template_name = 'doorstep/index.html'
    context_object_name = 'all_hotels'

    def get_queryset(self):
        return Hotel.objects.all().order_by('rating').reverse()[:3]

Now, i need to run this queryset Hotel.objects.all().order_by('star').reverse()[:3] from same IndexView and pass context_object_name from this querset to same template_name.

I get the value as {% for hotel in all_hotels %} in the template

like image 258
Space Avatar asked Apr 13 '17 09:04

Space


1 Answers

Override get_context_data and add any additional querysets to the context.

class IndexView(generic.ListView):
    template_name = 'doorstep/index.html'
    context_object_name = 'all_hotels'

    def get_queryset(self):
        return Hotel.objects.all().order_by('rating').reverse()[:3]

    def get_context_data(self, **kwargs):
        context = super(IndexView, self).get_context_data(**kwargs)
        context['star_hotels'] = Hotel.objects.all().order_by('star').reverse()[:3]
        # Add any other variables to the context here
        ...
        return context

You can now access {{ star_hotels }} in your template.

like image 195
Alasdair Avatar answered Nov 14 '22 22:11

Alasdair