Python 如何在Django中创建一个显示在模板中的计数器?
型号.pyPython 如何在Django中创建一个显示在模板中的计数器?,python,django,templates,view,count,Python,Django,Templates,View,Count,型号.py class Coche(models.Model): matricula = models.CharField(max_length=7,primary_key=True) class Index(ListView): model = Coche total_coches = Coche.objects.filter(reserved=False, sold=False) 视图.py class Coche(models.Model):
class Coche(models.Model):
matricula = models.CharField(max_length=7,primary_key=True)
class Index(ListView):
model = Coche
total_coches = Coche.objects.filter(reserved=False, sold=False)
视图.py
class Coche(models.Model):
matricula = models.CharField(max_length=7,primary_key=True)
class Index(ListView):
model = Coche
total_coches = Coche.objects.filter(reserved=False, sold=False)
模板
<span class="text-primary">{{ total_coches.count }}</span> <span>coches disponibles</span></span>
{{total_coches.count}}coches可争议文件
###它没有显示我的应用程序拥有的汽车数量。有人知道是什么错吗### 要在Django通用视图中将上下文传递给模板,需要使用get_context_data mixin
class Index(ListView):
model = Coche
def get_context_data(self, *args, **kwargs):
context = super(Index, self).get_context_data(*args, **kwargs)
context['total_coches'] = Coche.objects.filter(reserved=False, sold=False)
return context
如果您只需要计数器而不是整个查询集,那么最好遵循黑潮在评论中的建议,并在您的视图中定义它
class Index(ListView):
model = Coche
def get_context_data(self, *args, **kwargs):
context = super(Index, self).get_context_data(*args, **kwargs)
context['total_coches'] = Coche.objects.filter(reserved=False, sold=False).count()
return context
然后在模板中,您只需使用
{{total_coches}
views.py文件的template_name=index.html。根据total_coches的名称,我猜您需要该行中的coches计数。那么,为什么不在你的视图中把计数放在同一行呢?非常感谢!