代码之家  ›  专栏  ›  技术社区  ›  V-Light

Django:如何找出RawQuetySet是否有行?没有count()方法

  •  1
  • V-Light  · 技术社区  · 16 年前

    我认为这个标题不言自明。

    results[0].id

    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
    

    建议?!

    1 回复  |  直到 16 年前
        1
  •  0
  •   gruszczy    16 年前

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

    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