Source Code Relation between class-based views and its Models

Viewed 27

According to Django official URL,

models.py

from django.db import models
    class Publisher(models.Model):
        name = models.CharField(max_length=30)
        address = models.CharField(max_length=50)
        city = models.CharField(max_length=60)
        state_province = models.CharField(max_length=30)
        ...

views.py

from django.views.generic import ListView
from books.models import Publisher

class PublisherList(ListView):
    model = Publisher

urls.py

from django.urls import path
from books.views import PublisherList

urlpatterns = [
    path('publishers/', PublisherList.as_view()),
]

In the template, a variable called object_list that contains all the publisher objects.

{% extends "base.html" %}

{% block content %}
    <h2>Publishers</h2>
    <ul>
        {% for publisher in object_list %}
            <li>{{ publisher.name }}</li>
        {% endfor %}
    </ul>
{% endblock %}

I have been deep diving into source code of django to find out exactly where Django explicitly put all objects of the Publisher model into the template context (object_list). But no luck so far, Can anyone share some insights please?

1 Answers

ListView is a child class of BaseListView. The object_list attribute is initialised here:

class BaseListView(MultipleObjectMixin, View):
    """A base view for displaying a list of objects."""
    def get(self, request, *args, **kwargs):
        self.object_list = self.get_queryset()  # <--
        ...

and the default implementation of the .get_queryset() method is defined in MultipleObjectMixin:

def get_queryset(self):
    """
    Return the list of items for this view.
    The return value must be an iterable and may be an instance of
    `QuerySet` in which case `QuerySet` specific behavior will be enabled.
    """
    ...
Related