如何从 Django 中的 QuerySet 获取倒数第二项?

How to get penultimate item from QuerySet in Django?

如何从 Django QuerySet 中获取倒数第二项?我试过my_queryset[-2](检查my_queryset长度是否大于1后)如下:

if len(my_queryset)>1:
     query = my_queryset[-2]

它 returns:

Exception Value: Negative indexing is not supported.

有什么"Django"方法可以得到这样的物品吗?

我唯一想到的是反转查询集并得到my_queryset[2],但我不确定它的效率。

编辑:

scans = self.scans.all().order_by('datetime')
if len(scans)>1:
    scan = scans[-2]

此代码产生错误

scans = self.scans.all().order_by('datetime')
if len(scans)>1:
    scan = scans[-2]

相当于

scans = self.scans.all().order_by('-datetime')
if len(scans)>1:
    scan = scans[1]

如果你想得到第二个,要使用的索引是 1 而不是 2 因为在 python 中偏移量从 0.[=17= 开始]

另请注意 django querysets are lazy,这意味着只要有适当的索引可用,您就可以在不影响性能的情况下改变主意。

QuerySets are lazy – the act of creating a QuerySet doesn’t involve any database activity. You can stack filters together all day long, and Django won’t actually run the query until the QuerySet is evaluated. Take a look at this example: