Django count() function



(我知道的菜鸟问题(大家好,我一直对count((函数有问题。 在我的网站上,我向数据库添加了一些项目,然后我想在主页上显示项目的数量,但没有显示计数。我真的不知道我做错了什么。

这是代码: View.py:

class homeView(TemplateView):
template_name = 'search/home.html'
def conto(self):
album = Info.objects.all().count()
return album

网页文件:

<h3 style="text-align:center;"> ALBUM TOTALI: {{album}} </h3>

您需要覆盖要继承的TemplateViewget_context_data方法:

class homeView(TemplateView):
template_name = 'search/home.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['album'] = Info.objects.all().count()
return context

你可以用以下方法渲染它:

<h3 style="text-align:center;"> ALBUM TOTALI: {{view.conto}} </h3>

这是有效的,因为ContextMixin[Django-doc] 将视图传递给名为view的模板,因此您可以使用view.conto访问该方法。

最新更新