简体   繁体   English

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

[英]last() and [] operator give different results

I have a model RSSFeed.我有一个模型 RSSFeed。 To get the last element in my DB, I do:要获取数据库中的最后一个元素,我执行以下操作:

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

I slice it to get the first 10 element in the query我将它切片以获取查询中的前 10 个元素

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

Using first and the bracket operator is consistent:使用 first 和括号运算符是一致的:

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

But using last and the bracket operator is not consistent:但是使用 last 和括号操作符不一致:

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

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

Why?为什么? I expect to get the same result for last() and [] above.我希望上面的 last() 和 [] 得到相同的结果。

RSSFeed.objects.last() and first_ten_feeds.last() seem to give the same result but that does not make sense to me. RSSFeed.objects.last()first_ten_feeds.last()似乎给出了相同的结果,但这对我来说没有意义。

The answer is in the code actually. 答案实际上在代码中。 QuerySet.last() is defined as QuerySet.last()定义为

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

and what QuerySet.reverse() basically does is to return a clone of the queryset with the direction of the order by clause reverted , so basically instead of QuerySet.reverse()基本作用是返回带有set order by子句的方向已还原的queryset的副本,因此基本上代替

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

the SQL query becomes: SQL查询变为:

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

so first_ten_feeds.last() will actually returns the same thing as RSSFeed.objects.last() . 因此first_ten_feeds.last()实际上会返回与RSSFeed.objects.last()相同的东西。

This behaviour doesn't really match the doc and is quite surprising, not to say totally unexpected, and I strongly suggest you fill in a bug report on django's issue tracker - either it's the expected behaviour (for the django devs at least) and then it should be clearly documented, or it's a plain bug. 这种行为与文档并不完全匹配,并且令人惊讶,更不用说完全出乎意料了,我强烈建议您填写有关django的问题跟踪器的错误报告-要么是预期的行为(至少对django开发人员而言),然后应该清楚地记录下来,或者这是一个普通的错误。

Just crossed with this question, I have a similar case:刚刚越过这个问题,我有一个类似的案例:

 elem = my_qs.last()
 elem in my_qs
>>> False
 elem
>>> <1 - 'elem 1'>    # <- wrong
 elem = list(my_qs)[-1]
 elem
>>> <2 - 'elem 2'>    # <- correct

Still don't know the reason for this.仍然不知道这是什么原因。

I also tried to apply some ordering, as suggested for later versions of Django, but the result is the same.我也尝试应用一些排序,如 Django 的更高版本所建议的那样,但结果是一样的。

elem = my_qs.all().order_by('pk').last()
elem
>>> <1 - 'elem 1'>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM