简体   繁体   中英

Django CBVs: get_queryset() and get_context_data()?

What is the difference between get_queryset() and get_context_data() in a ListView (and what is their relationship).

And what gets passed as **kwargs in get_context_data(self, **kwargs) for example in path(' ', SomeViewList.as_view()) ?

My question applies to both the default methods and where applicable as overridden methods.

get_queryset

This method determines the list of objects that you want to display. It will give you all the models that you specified in your view by default, but you can override it and apply filters, sort, etc. Documentation .

class FilteredAuthorView(ListView):
    template_name = 'authors.html'
    model = Author

    def get_queryset(self):
        # original qs
        qs = super().get_queryset() 
        # filter by a variable captured from url, for example
        return qs.filter(name__startswith=self.kwargs['name'])

get_context_data

This method is used to populate a dictionary as a template context. For example, ListView s will populate the result from get_queryset() (not calling the actual function) but you also have the flexibility to render extra data into the context.

def get_context_data(self, **kwargs):
    data = super().get_context_data(**kwargs)
    data['page_title'] = 'Authors'
    return data

These are two separate methods so there isn't a direct relationship between them. I will consider get_context_data to be more complicated than get_queryset as you can append custom things into your context.

About the keyword arguments (kwargs), Django needs it to call the base implementation (which is to get the default models) before adding your custom things, even if you don't need to. The kwargs will include the model, template name, etc. that comes with your view. Documentation

Reference

EDIT

I have a view here, and I tried to print out the context data:

class JSONProfileView(JSONResponseMixin, DetailView):
    model = User
    template_name = 'accounts/dashboard/profile-json.html'

    def get_context_data(self, **kwargs):
        print(', '.join(['{}={!r}'.format(k, v) for k, v in kwargs.items()]))
        data = serializers.serialize('json', self.get_queryset())
        return data

I got this:

object=<User: userslug>

and it led me to believe that the keyword arguments are retrieved from the view object itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM