Diference between get_context_data and queryset in Django generic views?
Asked Answered
G

3

5

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

Griseous answered 29/6, 2017 at 10:51 Comment(6)
How are they doing the same thing, get_context_data() returns a context dict. queryset is a Django QuerySet of instances.Uniseptate
they achieve the same thingGriseous
They dont... what does the first line of the get_context_data docs say?... What is your interpretation of what they both do that makes you think they are the same?Disrespect
do you understand the difference between a dict and a queryset??Takashi
queryset = Publisher.objects.all() looks the same as context['book_list'] = Book.objects.all()Griseous
not what they are is what they do, but that is why I'm asking from experts to illuminate.Griseous
U
7

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.

Uniseptate answered 29/6, 2017 at 11:5 Comment(0)
J
4

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.

Justitia answered 29/6, 2017 at 11:0 Comment(0)
M
1

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.

Melvin answered 29/6, 2017 at 12:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.