last()和[]运算符给出不同的结果

2024-09-30 16:23:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个RSSFeed模型。 要获取数据库中的最后一个元素,我需要:

RSSFeed.objects.last()
# Output: <RSSFeed: www.sooperarticles.com>

我对它进行切片以获得查询中的前10个元素

first_ten_feeds = RSSFeed.objects.all()[:10]

使用first和方括号运算符是一致的:

first_ten_feeds.first()
# Output: <RSSFeed: pressetext News>
first_ten_feeds[0]
# Output: <RSSFeed: pressetext News>

但使用last和bracket运算符不一致:

first_ten_feeds[9]
# Output: <RSSFeed: FinanzNachrichten.de: Nachrichten zu IT-Dienstleistungen>

first_ten_feeds.last()
# Output: <RSSFeed: www.sooperarticles.com>

为什么?对于上面的last()和[],我希望得到相同的结果。你知道吗

RSSFeed.objects.last()first_ten_feeds.last()似乎给出了相同的结果,但这对我来说没有意义。你知道吗


Tags: 模型com元素outputobjectswww运算符first
1条回答
网友
1楼 · 发布于 2024-09-30 16:23:46

答案其实就在代码里。QuerySet.last()定义为

    for obj in (self.reverse() if self.ordered else self.order_by('-pk'))[:1]:
        return obj

QuerySet.reverse()基本上是返回queryset with the direction of the ^{} clause reverted的克隆,所以基本上不是

SELECT (...) from yourmodel ORDER BY somefield ASC LIMIT 10

SQL查询变为:

SELECT (...) from yourmodel ORDER BY somefield DESC LIMIT 10

所以first_ten_feeds.last()将实际返回与RSSFeed.objects.last()相同的东西。你知道吗

这种行为doesn't really match the doc非常令人惊讶,更不用说完全出乎意料,我强烈建议您在django的问题跟踪程序上填写一份bug报告——要么它是预期的行为(至少对于django开发人员而言),然后应该清楚地记录它,要么它是一个普通的bug。你知道吗

相关问题 更多 >