1、ListView:
只需要在views.py文档中引用此类,即可很快生成template所需的list:
from django.views.generic import ListView from books.models import Publisher class PublisherList(ListView): model = Publisher #简洁!不需要任何额外的get方法然后,即可对template/books/publisher_list.html进行简单渲染:
{% block content %} <h2>Publishers</h2> <ul> {% for publisher in object_list %} #或者:publiser_list(默认生成,model名称与list用下划线连接),该名字可以自己在view函数中指定:context_object_name = 'my_special_apply',然后用my_special_apply替换掉object_list即可 <li>{{ publisher.name }}</li> {% endfor %} </ul> {% endblock %}
而若想展示指定的数据(即先作筛选),则只需修改PublisherList类:
class PublisherList(ListView): queryset = Publisher.objects.filter(筛选条件) #简洁!甚至不需要指定model
很明显上面的写法中筛选条件不能做到动态进行,而只能写死,要做到动态,只需override ListView中的get_queryset(self)方法:
class PublisherList(ListView): # model = ApplyInfo #无需指定model def get_queryset(self): pub_name = self.request.GET.get("publisher_name", "") # addr = "上海" return Publisher.objects.filter(publisher_name=pub_name)然后配合下面的函数来丰富context的内容
def get_context_data(self, **kwargs): context = super(Publisher, self).get_context_data(**kwargs) context['title'] = "demosd" #可加入更多额外的信息来丰富context return context
2、DetailView
当ListView提供的内容不足以用来展示时,我们需要其它更具体的信息,此时可用DetailView:
from django.views.generic import DetailView from books.models import Publisher, Book class PublisherDetail(DetailView): model = Publisher def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super(PublisherDetail, self).get_context_data(**kwargs) # Add in a QuerySet of all the books context['book_list'] = Book.objects.all() return context这样,context对象又多了一个key为book_list的数据。