Post Image

Django Access QuerySet from get_context_data

I find there are times when working with class based views in Django that I need to add some context variables to use in my template that is based off of the query set. You do not need to run the get_queryset method again which will make a second query to the database, instead you can access it in a class variable directly. In this post I show you with some boiler plate code how to accomplish this by referencing the object_list variable.

 

Base Code

from django.views.generic import ListView
from .models import MyModel

class MyView(ListView):
    template_name = 'mytemplate.html'
    model = MyModel
    paginate_by = 50

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        return context

In the code above I have a view which inherits from ListView and I have it setup with a model, specific template, and to paginate. Lastly I have the get_context_data method overridden but I do not have any additional Logic

 

Because I am paginating my results, within my template when I am iterating over the object_list context variable displaying my results, I will only have access to 50, but I want to display the total results somewhere. Below I focus on the get_context_data method and add the code for counting the total results from the get_queryset method.

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context['total_results'] = self.object_list.count()
    return context

You can see that I add one line which is is getting a count of the self.object_list and setting the results to the context variable total_results.

 

What is the object_list Variable

For class based views that have the get_queryset method, after the get_queryset method is run the object_list variable will be set to the output of get_queryset. Because get_queryset is run before get_context_data we have access to reference the data from get_queryset.

 

 



Comments (0)
Leave a Comment