根据Django 官方网址,
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
) 的确切位置。但是到目前为止还没有运气,有人可以分享一些见解吗?