views:

24

answers:

1

Hello, I think the title speaks for itself.

I have a complex query with a subquery, but sometimes it returns no values, which is absolutely normal. But I can not prevent the ValueError message, cuz I am not able to find out whether RawQuerySet is empty or not. The RQS object is always present, but if I try to access it's first row results[0].id I get an error

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 1379, in __getitem__
    return list(self)[k]
IndexError: list index out of range

Suggestions ?!

A: 

Catch the exception?

try:
    return results[0].id
except IndexError:
    pass # no rows returned

or

import itertools

results_list = []
try:
    for i in itertools.count(0):
      results_list.append(results[i])
except IndexError:
    pass # no more rows
return results_list
gruszczy
Yeah, but how? I use the result in other function which calculates the font-size for tags.
V-Light
I changed it a little, to return the value. In second example you get the whole list of results, where you can use len. Simply work on the new list now.
gruszczy