[英]django get_queryset() is redundant, since we have get_context_data()?
I have been always wondering if get_queryset() is redundant in django. 我一直想知道get_queryset()在django中是否多余。 As we know, get_queryset() returns a list of objects back to the page, but to return this list of objects, we can also always specify it in get_context_data(), and get_context_data() can return many more variables, not just a list.
众所周知,get_queryset()将对象列表返回到页面,但是要返回此对象列表,我们也可以始终在get_context_data()中指定它,并且get_context_data()可以返回更多的变量,而不仅仅是列表。 An example can be seen as follows:
可以看到一个示例,如下所示:
Return a list of children book by get_queryset()
通过get_queryset()返回儿童读物的列表
from django.views.generic import ListView
from books.models import Book
class ChildrenBook(ListView):
model = Book
def get_queryset(self, *args, **kwargs):
qset = super(BookListView, self).get_queryset(*args, **kwargs)
return qset.filter(type="children")
Return a list of children book by get_context_data()
通过get_context_data()返回儿童读物的列表
from django.views.generic import ListView
from books.models import Book
class ChildrenBook(ListView):
model = Book
def get_context_data(self, **kwargs):
context = super(PublisherDetail, self).get_context_data(**kwargs)
context['children_book_list'] = Book.objects.filter(type="children")
return context
To the best of my knowledge, I do not find anything that get_queryset() can do but get_context_data cannot. 据我所知,我找不到get_queryset()可以做的任何事情,但是get_context_data无法做到。 Anyone can find some situation where only get_queryset() can be used and illustrate its necessity?
任何人都可以找到只能使用get_queryset()并说明其必要性的情况吗?
If you take a look at the actual django source code you'll see why overloading only get_context_data
is a bad idea unless you want to have to rewrite a whole bunch of code: 如果看一下实际的django源代码,您将明白为什么只重载
get_context_data
是一个坏主意,除非您想重写一堆完整的代码:
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)
Essentially, not overloading the get_queryset
method won't handle cases like when there are no records in the filter because the object_list
property won't be set correctly. 本质上,不重载
get_queryset
方法将无法处理诸如过滤器中没有记录之类的情况,因为object_list
属性的设置不正确。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.