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 li开发者_StackOverflow社区st(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 ?
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
精彩评论