Is there a sorting of the Django List model?

I use ListViewclass-based in my views, and I was wondering if there is a way to display the model object set in the template by sorting it. This is what I still have:

My views:

class Reviews(ListView):
    model = ProductReview
    paginate_by = 50
    template_name = 'review_system/reviews.html'

The model ProductReviewhas a field date_created. I would like to sort the date in descending order. How can i achieve this?

+4
source share
2 answers

Set the attribute orderingfor the view.

class Reviews(ListView):
    model = ProductReview
    paginate_by = 50
    template_name = 'review_system/reviews.html'

    ordering = ['-date_created']

If you need to dynamically reorder, you can use instead get_ordering.

class Reviews(ListView):
    ...
    def get_ordering(self):
        ordering = self.GET.get('ordering', '-date_created')
        # validate ordering here
        return ordering

If you always sort a fixed date field, you might be interested 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.

+11

get_queryset:

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')
+1

Source: https://habr.com/ru/post/1671898/


All Articles