synclabs
synclabs

Reputation: 277

Model IndexError after checking count()

Here's my code:

    qs = MyModel.objects.filter(blah = blah)
    if qs.count() > 0:
        a = qs[0].value

File "/home/libs/django/db/models/query.py", line 189, in __getitem__
   return list(qs)[0]

IndexError: list index out of range

Is there any possibilty to cause this error, other than the record being deleted from the database by a concurrent process ?

Upvotes: 1

Views: 187

Answers (1)

Jeffrey Bauer
Jeffrey Bauer

Reputation: 14080

Your code is not considering the possibility that no records are returned by the filter. Even though you use the qs.count() conditional, your return value assumes objects were returned. Perhaps you might consider a function:

def myquery():
    qs = MyModel.objects.filter(blah = blah)
    try:
        return qs[0].value
    except IndexError:
        return None  # or raise an exception

Upvotes: 1

Related Questions