Using get, get_queryset, get_context_data in Django CBVs

When I first started learning Django I had a lot of questions and while the Django documentation is absolutely excellent, sometimes you just may not know where to start. Which methods to use and override is pretty cut and dry for the experienced Djangonaut but for many first-time starters it can be a little confusing. Which is why I’ve decided to help clear up the confusion for beginners. Let’s get started.

The get method

You should override the get method when you want perform some data processing or logic before you want a request to be processed by the view. There are many reason’s why you would want to do this. Maybe you have page that requires a special token to be verified before a view is display to a user? Below is a quick and dirty example of overriding the get method:

overriding get method

The get_queryset method

The get_queryset method is used whenever data is being listed by a view(ListView). You override this method when you want a query beyond the default implemenation. For example, without overriding  get_queryset the view will retrieve all data from the database. By overriding this method you can fine tune your search query to display filtered information. A common use case is if you need to filter out table data that is specific to a certain user, profile or any other information that may be contained in the database, like an is_active field. Check out the example below:

overriding get_queryset

The get_context_data method

Last but not least is the get_context_data method. Simply put this method is used when you want to send data to the template context to be displayed or processed via the template that is not provided via get_queryset. Check out the example below:

Overriding get_context_data

And in the template you can reference the variable:

<ul>
{% for c in context %}
    <li>{{ c }}</li>
{% endfor %}
</ul>

For more information check out the Django docs!! If you have any questions, comments or concerns then feel free to let me know. Thanks.

2 thoughts on “Using get, get_queryset, get_context_data in Django CBVs

Leave a Reply to debo Cancel reply

Your email address will not be published. Required fields are marked *