When to use get, get_queryset, get_context_data in Django?

Hassan Raza
Nov 5 · 2 min read

get()

This is a top-level method, and there’s one for each HTTP verb — get(), post(), patch(), etc. You would override it when you want to do something before a request is processed by the view, or after. But this is only called when a form view is loaded for the first time, not when the form is submitted. Basic example in the documentation. By default it will just render the configured template and return the HTML.

class MyView(TemplateView):
# ... other methods
def get(self, *args, **kwargs):
print('Processing GET request')
resp = super().get(*args, **kwargs)
print('Finished processing GET request')
return resp

get_queryset()

Used by ListViews - it determines the list of objects that you want to display. By default it will just give you all for the model you specify. By overriding this method you can extend or completely replace this logic. Django documentation on the subject.

class FilteredAuthorView(ListView):
template_name = 'authors.html'
model = Author
def get_queryset(self):
# original qs
qs = super().get_queryset()
# filter by a variable captured from url, for example
return qs.filter(name__startswith=self.kwargs['name'])

get_context_data()

This method is used to populate a dictionary to use as the template context. For example, ListViews will populate the result from get_queryset() as author_list in the above example. You will probably be overriding this method most often to add things to display in your templates.

def get_context_data(self, **kwargs):
data = super().get_context_data(**kwargs)
data['page_title'] = 'Authors'
return data

And then in your template you can reference these variables.

<h1>{{ page_title }}</h1><ul>
{% for author in author_list %}
<li>{{ author.name }}</li>
{% endfor %}
</ul>

Credit: https://stackoverflow.com/questions/36950416/when-to-use-get-get-queryset-get-context-data-in-django

Hassan Raza

Written by

Software Engineer | ML Engineer | Integration Engineer | Writer at Medium’s Noteworthy — The Journel Blog

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade