开发者

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜