89👍
✅
Set the ordering
attribute for the view.
class Reviews(ListView):
model = ProductReview
paginate_by = 50
template_name = 'review_system/reviews.html'
ordering = ['-date_created']
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
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"
Note that ArchiveIndexView
won’t show objects with a date in the future unless you set allow_future
to True
.
10👍
Why don’t you override the get_queryset
method like this:
class Reviews(ListView):
model = ProductReview
paginate_by = 50
template_name = 'review_system/reviews.html'
def get_queryset(self):
return YourModel.objects.order_by('model_field_here')
- [Django]-How to format dateTime in django template?
- [Django]-Django filter JSONField list of dicts
- [Django]-How do I match the question mark character in a Django URL?
Source:stackexchange.com