![]() |
VOOZH | about |
A ListView is a built-in class-based view used to show multiple records from a database. It handles data retrieval automatically, reducing the code required.
Example: Consider a project named 'geeksforgeeks' having an app named 'geeks'. After you have a project and an app, let's create a model of which we will be creating instances through our view.
In geeks/models.py:
After creating this model, we need to run two commands in order to create Database.
Python manage.py makemigrations
Python manage.py migrate
Create instances of this model using the Django shell by running the following command in the terminal:
Python manage.py shell
Enter following commands:
>>> from geeks.models import GeeksModel
>>> GeeksModel.objects.create( title="title1", description="description1")
>>> GeeksModel.objects.create(title="title2", description="description2")
>>> GeeksModel.objects.create(title="title3", description="description3")
Now that the backend setup complete, verify that instances have been created by visiting: http://localhost:8000/admin/geeks/geeksmodel/
π django-listview-check-models-instances
To create a ListView, it is only necessary to specify the model. Djangoβs ListView will then look for a template named app_name/modelname_list.html. In this case, expected template path is geeks/templates/geeks/geeksmodel_list.html
In geeks/views.py:
Create a url path to map the view. In geeks/urls.py:
Create a template in templates/geeks/geeksmodel_list.html:
Visit http://localhost:8000/ to view the list of all model instances displayed through the Class-Based ListView.
π django-listview-class-based-views
By default, ListView displays all instances of a model in the order they were created. To modify the order or filter the results, get_queryset() method can be overridden.
In geeks/views.py:
Verify whether the instances are now displayed in reverse order.
π django-reverse-list-view-class
This approach allows complete control over the queryset, enabling modification, filtering or ordering as required.