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.
These are completely different things.
get_context_data()
is used to generate dict of variables that are accessible in template. queryset
is Django ORM queryset that consists of model instances
Default implementation of get_context_data()
in ListView
adds return value of get_queryset()
(which simply returns self.queryset
by default) to context as objects_list
variable.
Why not have a look at the code.
http://ccbv.co.uk/projects/Django/1.11/django.views.generic.list/ListView/
Clicking on the get() method shows that it calls get_queryset() method to get the queryset - which is usually iterated over in a ListView.
Further down it calls get context_data() where extra variables can be passed to the template.
© 2022 - 2024 — McMap. All rights reserved.
get_context_data()
returns a context dict.queryset
is a Django QuerySet of instances. – Uniseptateget_context_data
docs say?... What is your interpretation of what they both do that makes you think they are the same? – Disrespect