Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Diference between get_context_data and queryset in Django generic views?

What is the difference between get_context_data and queryset in Django generic views? They seem to do the same thing?

like image 448
Bootstrap4 Avatar asked Dec 18 '22 06:12

Bootstrap4


1 Answers

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 object_list. 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['some_thing'] = 'some_other_thing'
    return data

And then in your template you can reference these variables.

<h1>{{ some_thing }}</h1>

<ul>
{% for item in object_list %}
    <li>{{ item.name }}</li>
{% endfor %}    
</ul>

This method is only used for providing context for the template.

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.

like image 188
zaidfazil Avatar answered Jan 19 '23 00:01

zaidfazil