modelsに基づく汎用ビュー
以下のモデルを考える
# models.py
from django.db import modelsclass 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)
country = models.CharField(max_length=50)
website = models.URLField()class Meta:
ordering = ["-name"]def __unicode__(self):
return self.nameclass Book(models.Model):
title = models.CharField(max_length=100)
authors = models.ManyToManyField('Author')
publisher = models.ForeignKey(Publisher)
publication_date = models.DateField()
Publisherの全ての行を表示するには
from django.conf.urls.defaults import *
from django.views.generic import ListView
from books.models import Publisherurlpatterns = patterns('',
(r'^publishers/$', ListView.as_view(
model=Publisher,
)),
)
テンプレートを書く
/path/to/project/books/templates/books/publisher_list.html
{% extends "base.html" %}{% block content %}
Publishers
{% for publisher in object_list %}
- {{ publisher.name }}
{% endfor %}
{% endblock %}