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]
and
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:
What approach is better? Or when setting queryset
variable is better than override the get_queryset
method? And vice versa.
Model and queryset are very similar, but queryset's value if provided overrides that of model's.
Model is what type of Object this view displays.
Overriding get_queryset controls what specific instances this view displays (ex: the last 5 instances created)
From Django's documentation:
model:
queryset:
get_queryset:
In your example, overriding
queryset
andget_queryset
have the same effect. I would slightly favour settingqueryset
because it's less verbose.When you set
queryset
, the queryset is created only once, when you start your server. On the other hand, theget_queryset
method is called for every request.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:Another example where
get_queryset
is useful is when you want to filter based on a callable, for example, return today's polls:If you tried to do the same thing by setting
queryset
, thendate.today()
would only be called once, when the view was loaded, and the view would display incorrect results after a while.inside class just include
if you don't use the queryset anywhere.
This worked for me.
Thanks
Other answers have missed an important implication of the fact that the
queryset
attribute is evaluated when the process starts. Because you aren't just creating a queryset, you're actually slicing it, the query will be evaluated at that point. That means that you will only ever get the top 5 polls at that moment, and they won't refresh even if you create another one, until the process is restarted.This is exactly when you should be using
get_queryset()
.The queryset attribute is used internally, always use the method (you will often have to perform custom queries based on request or session vars for example)