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

时间:2019-02-01 10:23:32

标签: python django

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

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

我将其切片以获得查询中的前10个元素

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

首先使用且方括号运算符一致:

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

但是使用last和方括号运算符不一致:

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()似乎给出了相同的结果,但这对我来说没有意义。

1 个答案:

答案 0 :(得分:2)

答案实际上在代码中。 QuerySet.last()被定义为

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

QuerySet.reverse()的主要作用是返回查询集with the direction of the order by 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问题跟踪工具的错误报告-要么是预期的行为(至少对django开发人员而言),那么应该清楚地记录下来,或者这是一个普通的错误。

相关问题