5

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

Håken Lid
  • 22,318
  • 9
  • 52
  • 67
Bootstrap4
  • 3,671
  • 4
  • 13
  • 17
  • 1
    How are they doing the same thing, `get_context_data()` returns a context dict. `queryset` is a Django QuerySet of instances. – zaidfazil Jun 29 '17 at 10:52
  • 3
    they achieve the same thing – Bootstrap4 Jun 29 '17 at 10:56
  • 1
    They dont... what does the first line of [the `get_context_data` docs](https://docs.djangoproject.com/en/1.11/ref/class-based-views/mixins-simple/) say?... What is your interpretation of what they both do that makes you think they are the same? – Sayse Jun 29 '17 at 10:57
  • do you understand the difference between a dict and a queryset?? – Exprator Jun 29 '17 at 10:59
  • queryset = Publisher.objects.all() looks the same as context['book_list'] = Book.objects.all() – Bootstrap4 Jun 29 '17 at 11:19
  • 1
    not what they are is what they do, but that is why I'm asking from experts to illuminate. – Bootstrap4 Jun 29 '17 at 11:32

3 Answers3

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.

zaidfazil
  • 9,017
  • 2
  • 24
  • 47
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.

bakatrouble
  • 1,746
  • 13
  • 19
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.

wobbily_col
  • 11,390
  • 12
  • 62
  • 86