使用get_queryset()方法还是设置queryset变量? [英] Use get_queryset() method or set queryset variable?
问题描述
这两个代码在第一次出现时是相同的:
These two pieces of code are identical at the first blush:
class IndexView(generic.ListView):
template_name = 'polls/index.html'
context_object_name = 'latest_poll_list'
queryset = Poll.active.order_by('-pub_date')[:5]
和
class IndexView(generic.ListView):
template_name = 'polls/index.html'
context_object_name = 'latest_poll_list'
def get_queryset(self):
return Poll.active.order_by('-pub_date')[:5]
它们之间是否有任何区别?如果是这样的话:
Is there any difference between them? And if it is:
哪种方法更好?还是设置 queryset
变量比覆盖 get_queryset
方法更好?
What approach is better? Or when setting queryset
variable is better than override the get_queryset
method? And vice versa.
推荐答案
在您的示例中,覆盖 queryset
和 get_queryset
具有相同的效果。我会稍微喜欢设置 queryset
,因为它不太冗长。
In your example, overriding queryset
and get_queryset
have the same effect. I would slightly favour setting queryset
because it's less verbose.
当您设置 queryset
,启动服务器时,只会创建一次查询集。另一方面,每个请求都调用 get_queryset
方法。
When you set queryset
, the queryset is created only once, when you start your server. On the other hand, the get_queryset
method is called for every request.
这意味着 get_queryset
在要动态调整查询时非常有用。例如,您可以返回属于当前用户的对象:
That means that get_queryset
is useful if you want to adjust the query dynamically. For example, you could return objects that belong to the current user:
class IndexView(generic.ListView):
def get_queryset(self):
"""Returns Polls that belong to the current user"""
return Poll.active.filter(user=self.request.user).order_by('-pub_date')[:5]
另一个示例,其中 get_queryset
很有用,当您想基于可调用项进行过滤时,例如返回今天的民意调查:
Another example where get_queryset
is useful is when you want to filter based on a callable, for example, return today's polls:
class IndexView(generic.ListView):
def get_queryset(self):
"""Returns Polls that were created today"""
return Poll.active.filter(pub_date=date.today())
如果您尝试通过设置 queryset
,然后 date.today()
只会在加载视图时被调用一次,并且一段时间后视图将显示错误的结果。
If you tried to do the same thing by setting queryset
, then date.today()
would only be called once, when the view was loaded, and the view would display incorrect results after a while.
class IndexView(generic.ListView):
# don't do this!
queryset = Poll.active.filter(pub_date=date.today())
这篇关于使用get_queryset()方法还是设置queryset变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!