設置視圖的ordering
屬性。
class Reviews(ListView):
model = ProductReview
paginate_by = 50
template_name = 'review_system/reviews.html'
ordering = ['-date_created']
如果您需要動態更改排序,則可以使用get_ordering
代替。
class Reviews(ListView):
...
def get_ordering(self):
ordering = self.GET.get('ordering', '-date_created')
# validate ordering here
return ordering
如果您總是對固定日期字段進行排序,您可能會對ArchiveIndexView
感興趣。
from django.views.generic.dates import ArchiveIndexView
class Reviews(ArchiveIndexView):
model = ProductReview
paginate_by = 50
template_name = 'review_system/reviews.html'
date_field = "date_created"
注意ArchiveIndexView
不會在將來的日期顯示的對象,除非你設置allow_future
到True
。
我喜歡ArchiveIndexView,它的伎倆,但模板具有允許通過點擊標題排序列的表。當我這樣做時,這不起作用,你知道我該如何使它在那裏工作? – DeA
如果您按其他字段進行排序,則聽起來像歸檔索引視圖不合適。 – Alasdair