Reputation: 7731
I have a ListView in Django whose get_queryset() method will sometimes need to return no results. I've tried three ways to do this:
return EmptyQuerySet()
return Model.objects.none()
return Model.objects.filter(pk=-1)
Each one of these returns a slightly different object.
django.db.models.query.EmptyQuerySet
with its model attribute set to None
django.db.models.query.EmptyQuerySet
with its model attribute set to Model
django.db.models.query.QuerySet
with its model attribute set to Model
Only the third option works with the class based ListView. The other options crash on an attribute error when the ListView tries to access the model attribute. This surprises me and is a pain as it requires me to import Model in places where that can cause MRO issues.
What am I doing wrong/what should I be doing differently?
Update: The question then is, what is the right way to return an empty queryset via the class view method get_queryset()
?
Update: Here is the line in Django's generic views that hits an attribute error when trying access the model
attribute: https://github.com/django/django/blob/stable/1.5.x/django/views/generic/list.py#L166.
Upvotes: 43
Views: 34064