有Django List View模型排序吗? [英] Is there Django List View model sort?
问题描述
我在基于类的视图中使用了 ListView
,我想知道是否有一种方法可以对模板上的模型对象集进行排序。这是我到目前为止的内容:
I'm using ListView
in my Class Based Views and I was wondering if there was a way to display the model object set on the template by sorting it. This is what I have so far:
我的观点:
class Reviews(ListView):
model = ProductReview
paginate_by = 50
template_name = 'review_system/reviews.html'
模型 ProductReview
有一个 date_created
字段。我想按降序对日期进行排序。我该如何实现?
The model ProductReview
has a date_created
field. I'd like to sort the date in descending order. How can I achieve this?
推荐答案
设置 ordering
视图的属性。
Set the ordering
attribute for the view.
class Reviews(ListView):
model = ProductReview
paginate_by = 50
template_name = 'review_system/reviews.html'
ordering = ['-date_created']
如果您需要动态更改顺序,则可以使用 get_ordering
。
If you need to change the ordering dynamically, you can use get_ordering
instead.
class Reviews(ListView):
...
def get_ordering(self):
ordering = self.request.GET.get('ordering', '-date_created')
# validate ordering here
return ordering
如果您始终对固定日期字段进行排序,则可能对 ArchiveIndexView
。
If you are always sorting a fixed date field, you may be interested in the 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
。
Note that ArchiveIndexView
won't show objects with a date in the future unless you set allow_future
to True
.
这篇关于有Django List View模型排序吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!