ListView – Class Based Views 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. They do not replace function-based views, but have certain differences and advantages when compared to function-based views: 

  • Organization of code related to specific HTTP methods (GET, POST, etc.) can be addressed by separate methods instead of conditional branching.
  • Object oriented techniques such as mixins (multiple inheritance) can be used to factor code into reusable components.

Class based views are simpler and efficient to manage than function-based views. A function based view with tons of lines of code can be converted into a class based view with few lines only. This is where Object Oriented Programming comes into impact. 

Django List View – Function Based Views

Illustration of How to create and use List view using an Example. Consider a project named w3wiki having an app named Beginner. 

Refer to the following articles to check how to create a project and an app in Django. 

After you have a project and an app, let’s create a model of which we will be creating instances through our view. In Beginner/models.py, 

Python3




# import the standard Django Model
# from built-in library
from django.db import models
  
# declare a new model with a name "BeginnerModel"
class BeginnerModel(models.Model):
 
    # fields of the model
    title = models.CharField(max_length = 200)
    description = models.TextField()
 
    # renames the instances of the model
    # with their title name
    def __str__(self):
        return self.title


After creating this model, we need to run two commands in order to create Database for the same. 

Python manage.py makemigrations
Python manage.py migrate

Now let’s create some instances of this model using shell, run form bash, 

Python manage.py shell

Enter following commands  

>>> from Beginner.models import BeginnerModel
>>> BeginnerModel.objects.create(
                       title="title1",
                       description="description1").save()
>>> BeginnerModel.objects.create(
                       title="title2",
                       description="description2").save()
>>> BeginnerModel.objects.create(
                       title="title2",
                       description="description2").save()

Now we have everything ready for back end. Verify that instances have been created from http://localhost:8000/admin/Beginner/Beginnermodel/ 

Class Based Views automatically setup everything from A to Z. One just needs to specify which model to create ListView for, then Class based ListView will automatically try to find a template in app_name/modelname_list.html. In our case it is Beginner/templates/Beginner/Beginnermodel_list.html. Let’s create our class based view. In Beginner/views.py, 

Python3




from django.views.generic.list import ListView
from .models import BeginnerModel
 
class BeginnerList(ListView):
 
    # specify the model for list view
    model = BeginnerModel


Now create a url path to map the view. In Beginner/urls.py, 

Python3




from django.urls import path
 
# importing views from views..py
from .views import BeginnerList
urlpatterns = [
    path('', BeginnerList.as_view()),
]


Create a template in templates/Beginner/Beginnermodel_list.html, 

HTML




<ul>
    <!-- Iterate over object_list -->
    {% for object in object_list %}
    <!-- Display Objects -->
    <li>{{ object.title }}</li>
    <li>{{ object.description }}</li>
   
    <hr/>
    <!-- If object_list is empty  -->
    {% empty %}
    <li>No objects yet.</li>
    {% endfor %}
</ul>


Let’s check what is there on http://localhost:8000/ 

Manipulate Queryset in ListView

By default ListView will display all instances of a table in the order they were created. If one wants to modify the sequence of these instances or the ordering, get_queryset method need to be overridden. 
In Beginner/views.py, 

Python3




from django.views.generic.list import ListView
from .models import BeginnerModel
   
class BeginnerList(ListView):
   
    # specify the model for list view
    model = BeginnerModel
   
    def get_queryset(self, *args, **kwargs):
        qs = super(BeginnerList, self).get_queryset(*args, **kwargs)
        qs = qs.order_by("-id")
        return qs


Now check, if the order of instances has been reversed. 

This way one can modify the entire queryset in any manner possible.