QuerySets aren’t Lists

June 04, 08 by

Problem

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?>

This entry no have comments... but you can be first.

Leave a Reply


Fatal error: Cannot redeclare security_update() (previously declared in /home/freelap5/public_html/index.php:13) in /home/freelap5/public_html/index.php on line 27