I want to retrieve the 13 latest objects, which shows this in my shell:
>>> last_13_issues = Issue.objects.order_by('-id').order_by('-pub_date')[:13]
>>> print last_13_issues
[<Issue: X-Men v2 #18>, <Issue: Uncanny X-Men #543>, **<Issue: Herc #7>**, <Issue: X-Men: Schism #4>, <Issue: X-Men v2 #17>, <Issue: X-Men First Class: The High Hand #1>, <Issue: Astonishing X-Men #41>, <Issue: X-Men v2 #16>, <Issue: Generation Hope #10>, <Issue: X-Men: Schism #3>, <Issue: Uncanny X-Men #542>, <Issue: X-Men: Schism #2>, <Issue: New Mutants v3 #28>]
Note Herc #7, which is marked with ** **.
In my template, I have a slider that shows the 3 latest objects, and then the rest of the objects not in a slider. So, I did this:
latest_appearances = Issue.objects.order_by('-id').order_by('-pub_date')[:3]
more_latest_appearances = Issue.objects.order_by('-id').order_by('-pub_date')[4:14]
latest_appearances shows this:
[<Issue: X-Men v2 #18>, <Issue: X-Men: Schism #4>, <Issue: Uncanny X-Men #543>]
more_latest_appearances shows this:
[<Issue: X-Men v2 #17>, <Issue: X-Men First Class: The High Hand #1>, <Issue: X-Men v2 #16>, <Issue: Astonishing X-Men #41>, <Issue: X-Men: Schism #3>, <Issue: Uncanny X-Men #542>, <Issue: Generation Hope #10>, <Issue: X-Men: Schism #2>, <Issue: New Mutants v3 #28>, <Issue: Secret Avengers #15>]
Notice that Herc #7 is gone. Now, since I have it ordered by -pub_date, 4 of the issues in last_13_issues have the same pub_date, so what can I do to fix this? I have made sure that 3 issues show the same pub_date, but that’s obviously no help for when I have 4 issues with the same pub_date.
Ordering the issues only by id is no help either because sometimes I go back and add older issues, so sometimes issues with the highest id are not actually the latest issues.
Ok, odd. Case closed. I slice in the template, instead, and it works…which is weird that it doesn’t work in the views. But if anyone can figure out why, kudos to you!
Use
[3:]instead of[4:]for yourmore_latest_appearances.End index is non-inclusive for slicing:
In order to clarify things more, I’d suggest rewriting your code a little to look like this:
This way, you only do a single query and then split the results up, rather than doing separate queries which might return the results in differing order.