Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there Django List View model sort?

Tags:

python

django

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:

My views:

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

The model ProductReview has a date_created field. I'd like to sort the date in descending order. How can I achieve this?

like image 703
DeA Avatar asked Mar 09 '17 14:03

DeA


People also ask

What is a list view in Django?

List View refers to a view (logic) to display multiple instances of a table in the database. We have already discussed the basics of List View in List View – Function based Views Django. Class-based views provide an alternative way to implement views as Python objects instead of functions.

What are models and views in Django?

A Model is a source of information about our data. It contains behavioural aspects and other essential features of our data. Models are a way to create a database for a Django project. Each model maps to a single database table that is every time you create a model basically it is going to map to a database table.

What is generic view in Django?

Django offers an easy way to set those simple views that is called generic views. Unlike classic views, generic views are classes not functions. Django offers a set of classes for generic views in django. views. generic, and every generic view is one of those classes or a class that inherits from one of them.


1 Answers

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.

like image 66
Alasdair Avatar answered Oct 06 '22 14:10

Alasdair