基于 class 的视图与其模型之间的源代码关系

Source Code Relation between class-based views and its Models

根据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()),
]

在模板中,名为 object_list 的变量包含所有发布者对象。

{% extends "base.html" %}

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

我一直在深入研究 Django 的源代码,以找出 Django 明确将 Publisher 模型的所有对象明确放入模板上下文 (object_list) 的位置。但到目前为止运气不好,有人可以分享一些见解吗?

ListView 是 child class 的 BaseListViewobject_list 属性已初始化 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()  # <--
        ...

并且.get_queryset()方法的默认实现是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.
    """
    ...