Is there Django List View model sort?

前端 未结 2 1289
一整个雨季
一整个雨季 2021-02-02 10:41

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 hav

2条回答
  •  眼角桃花
    2021-02-02 11:14

    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.

提交回复
热议问题