gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 21:44:12 26 4
gpt4 key购买 nike

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

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

它返回:

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 开始。

另请注意 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:

关于python - 如何从 Django 中的 QuerySet 获取倒数第二项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41039166/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com