What is the difference between get_context_data
and queryset
in Django generic views? They seem to do the same thing?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With