Django IntroductionChapter 4. Create CRUD Web Application

Customize Views (1) – Change List Order

Customize Views (1) – Change List Order

Customizing Django Views to Change List Order

Using the queryset attribute and the order_by method, you can easily change the order of the list. Here, we'll explain how to use them with the employee learning app example.

Change the list data order

To change the order of the list on the List page based on the course title, edit the CourseList view by adding the yellow part of the code below. Also, comment out the model part as queryset and model have similar functionality.

employee_learning/views.py
class CourseList(ListView):
  # model = LearningCourse
    queryset = LearningCourse.objects.order_by('title')
      :

You can see that the order of the list is changed based on the course title.

Django List Page with changed order

Reverse order

To reverse the order, you need to just add '-' before the field name.

employee_learning/views.py
class CourseList(ListView):
  # model = LearningCourse
    queryset = LearningCourse.objects.order_by('-title')
      :

You can see that the order of the list is reversed.

Django List Page with reverse order

You can also learn this topic offline. Click AmazonKindle.

Django Introduction
Course Content