使用django,我创建了book class和bookmanager class.py。Bookmanager类具有计算包含关键字的书名的数量。如何使用基于Classe的视图将书名计数显示为HTML文件?
我知道如何使用基于函数的视图,而不是基于listView类的视图进行操作。
models.py
from django.db import models
# Create your models here.
class BookManager(models.Manager):
def title_count(self, keyword):
return self.filter(title__icontains=keyword).count()
class Book(models.Model):
title = models.CharField(max_length=100)
publication_date = models.DateField()
page_length = models.IntegerField(null=True, blank=True)
objects = BookManager()
def __unicode__(self):
return self.title
views.py
from django.shortcuts import render
from django.views.generic import ListView
from .models import Book
class BookViewPage(ListView):
model = Book
title_number = Book.objects.title_count('django')
def bookviewpage(request):
context ={
'count': Book.objects.title_count('django')
}
return render(request, 'books/book_list.html', context)
我想使用基于Classe的视图在HTML文件上显示书名。
您可以通过覆盖get_context_data
方法将项目添加到基于类视图的上下文中。
class BookViewPage(ListView):
model = Book
def get_context_data(self, **kwargs):
context = super(BookViewPage, self).get_context_data(**kwargs)
context['title_number'] = Book.objects.title_count('django')
return context
现在您可以在模板中使用{{ title_number }}
。
将title_number = Book.objects.title_count('django')
放在视图中不起作用,因为该代码在加载模块时运行,而不是当视图处理请求时。