QuerySets aren’t Lists
June 04, 08 byProblem
You have been playing with the database API and noticed that a returned query set looks a lot like a list:
>>> from mysite.polls.models import Poll,Choice >>> Poll.objects.all() [<Poll: What is up?>, <Poll: What is your favourite colour?>] ## looks a lot like a list to me
But, it doesn’t behave like a list in some cases.
Solution
Here are a couple of cases where the behaviour is not list-like and their solution.
In Python this is how we can test for an empty list:
>>> b=[] >>> b==[] True
This doesn’t work with a QuerySet?. You might try the following but it will fail:
>>> from mysite.polls.models import Poll,Choice >>> p = Poll.objects.filter(question__startswith=‘ZZZZZZZZZZZZ’) >>> p [] >>> p==[] False
The way to do it is test for p.count:
>>> from mysite.polls.models import Poll,Choice >>> p = Poll.objects.filter(question__startswith=‘ZZZZZZZZZZZZ’) >>> p [] >>> p.count() == 0 True
Another case occurs when you want to retrieve the last member of a QuerySet?:
>>> from mysite.polls.models import Poll,Choice >>> p = Poll.objects.all() >>> p [<Poll: What is up?>, <Poll: What is your favourite colour?>] >>> p[-1] Traceback (most recent call last): File “<console>”, line 1, in ? File “c:\python24\lib\site-packages\django-0.95-py2.4.egg\django\db\models\query.py”, line 98, in __getitem__ assert (not isinstance(k, slice) and (k >= 0)) \ AssertionError: Negative indexing is not supported.
The way I get the last member is:
>>> p[p.count()-1] <Poll: What is your favourite colour?>