Opened 6 years ago
Closed 6 years ago
#30151 closed Bug (invalid)
QuerySet.last() and [] operator give different results
Reported by: | Martin Ennemoser | Owned by: | nobody |
---|---|---|---|
Component: | Database layer (models, ORM) | Version: | 1.11 |
Severity: | Normal | Keywords: | |
Cc: | Triage Stage: | Unreviewed | |
Has patch: | no | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Description (last modified by )
I have a model 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
first_ten_feeds = RSSFeed.objects.all()[:10]
Using first and the bracket operator is consistent:
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:
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.
RSSFeed.objects.last() and first_ten_feeds.last() seem to give the same result but that does not make sense to me.
I already openend a SO question with the same content: https://stackoverflow.com/questions/54477472/last-and-operator-give-different-results
There I was suggested to open a bug.
Change History (3)
comment:1 by , 6 years ago
Description: | modified (diff) |
---|
comment:2 by , 6 years ago
Description: | modified (diff) |
---|
comment:3 by , 6 years ago
Component: | Uncategorized → Database layer (models, ORM) |
---|---|
Resolution: | → invalid |
Status: | new → closed |
Summary: | last() and [] operator give different results → QuerySet.last() and [] operator give different results |
Type: | Uncategorized → Bug |
As far as I can tell from the code you gave, the slice is operating on an unordered queryset. There's no guarantee as to what ordering the database will return.
last()
gives ordering by primary key if the queryset isn't ordered.