如何在没有IndexError的情况下访问特定索引处的QuerySet元素?

时间:2019-05-07 01:15:10

标签: python django

在检索Django查询集列表中倒数第二个元素时遇到麻烦。

我知道我可以这样过滤它:

 QuoteOfTheDay.objects.all().order_by('-id')[1]

但是我需要一种安全的方法来做到这一点,以便当它为空时,它不会返回

  

/列表索引超出范围时出现IndexError

2 个答案:

答案 0 :(得分:0)

您可以执行以下操作,使用count检查查询集中有多少项

[19-05-07 04:29:35:609 PDT] Starting execution
[19-05-07 04:29:35:620 PDT] SpreadsheetApp.getActiveSpreadsheet() [0 seconds]
[19-05-07 04:29:35:621 PDT] Spreadsheet.getActiveCell() [0 seconds]
[19-05-07 04:29:36:233 PDT] Range.getValue() [0.611 seconds]
[19-05-07 04:29:36:295 PDT] Range.setValue([3.0]) [0.061 seconds]
[19-05-07 04:29:36:620 PDT] Execution succeeded [0.678 seconds total runtime]

答案 1 :(得分:0)

您可以使用try-except块。

try:

    query_set = QuotesOfTheDay.objects.all().orderby('-id')[-1]
    ** other logic here **

except IndexError:
    print('No Quotes')