在Python / Django问题中切片对象

时间:2011-09-23 04:25:11

标签: python django django-views

我想检索13个最新的对象,这些对象在我的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>]

注意Herc#7,标有** **

在我的模板中,我有一个滑块显示3个最新的对象,然后其余的对象不在滑块中。所以,我这样做了:

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显示了这一点:

[<Issue: X-Men v2 #18>, <Issue: X-Men: Schism #4>, <Issue: Uncanny X-Men #543>]

more_latest_appearances显示了这一点:

[<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>]

请注意,Herc#7已经消失。现在,由于我按-pub_date排序,last_13_issues中的4个问题具有相同的pub_date,因此我该怎么做才能解决这个问题?我确保3个问题显示相同的pub_date,但是当我遇到同一个pub_date的4个问题时,这显然没有任何帮助。

id排序问题也无济于事,因为有时我会回过头来添加较旧的问题,因此有时候id最高的问题实际上并不是最新问题。

好的,奇怪的。案件结案。我在模板中切片,相反,它的工作原理......奇怪的是,它在视图中不起作用。但如果有人能弄明白为什么,请向你致敬!

1 个答案:

答案 0 :(得分:1)

[3:]使用[4:]代替more_latest_appearances

结束索引不包含切片:

>>> "abcdef"[:3]
'abc'
>>> "abcdef"[4:]
'ef'
>>> "abcdef"[3:]
'def'

为了澄清更多内容,我建议稍微重写一下代码,如下所示:

appearances = Issue.objects.order_by('-id').order_by('-pub_date')
latest_appearances = appearances[:3]
more_latest_appearances = appearances[3:14]

这样,您只需执行一次查询,然后将结果拆分,而不是执行单独的查询,这些查询可能会以不同的顺序返回结果。