When to use get, get_queryset, get_context_data in Django?

前端 未结 2 875
心在旅途
心在旅途 2020-11-28 00:35

I recently learned that you should override the get method when you specifically want to do something other than what the default view does:

class ExampleVie         


        
2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-28 01:35

    Let's look at the default implementation of ListView's get method:

    https://github.com/django/django/blob/92053acbb9160862c3e743a99ed8ccff8d4f8fd6/django/views/generic/list.py#L158

    class BaseListView(MultipleObjectMixin, View):
        """
        A base view for displaying a list of objects.
        """
        def get(self, request, *args, **kwargs):
            self.object_list = self.get_queryset()
            allow_empty = self.get_allow_empty()
    
            if not allow_empty:
                # When pagination is enabled and object_list is a queryset,
                # it's better to do a cheap query than to load the unpaginated
                # queryset in memory.
                if (self.get_paginate_by(self.object_list) is not None
                        and hasattr(self.object_list, 'exists')):
                    is_empty = not self.object_list.exists()
                else:
                    is_empty = len(self.object_list) == 0
                if is_empty:
                    raise Http404(_("Empty list and '%(class_name)s.allow_empty' is False.")
                            % {'class_name': self.__class__.__name__})
            context = self.get_context_data()
            return self.render_to_response(context)
    

    You will notice that get_queryset gets called in the first line. You can simply overwrite that if you just want to return your model's queryset after applying some filtering/ordering etc.

    You don't need to overwrite the whole get method for that because you will be missing on all this provided functionality i.e. pagination, 404 checks etc.

    get_context_data merges the resulting queryset together with context data like querystring parameters for pagination etc.

    What I would recommend would be to check with django's source every once in a while and try to understand it a little bit so that you can recognize the most appropriate method you can overwrite/replace.

提交回复
热议问题