【发布时间】:2022-01-19 15:57:49
【问题描述】:
我想知道如何在我的 django 模板的 for 循环中计算所有真/假布尔值,但我不确定如何在循环中实现这一点。我的目标是向用户展示有多少问题未解决/已解决。
让我们说这些是我的模型:
class Category(models.Model):
name = models.CharField(max_length=50)
class Question(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE)
title = models.CharField(max_length=50)
description = models.TextField(max_length=250)
solved = models.BooleanField(default=False)
列表视图:
class CategoryView(ListView):
model = Category
context_object_name = 'categories'
模板:
{% for category in categories %}
{{ category.name }} # I would like to show: 5/10 questions solved
{% for question in category.question_set.all %}
{{ question.name }}
{{ question.title }}
{{ question.description }}
{{ question.solved }}
{% endfor %}
{% endfor %}
通常我用.count 打印对象总数,例如:{{cagetories.count }}
但我不能在循环内执行此操作,因为它返回:1 1 1 1 1 1:
{% for question in category.question_set.all %}
{% if not question.solved %}
{{ question.count }} ## returns 1 1 1 1 1 1
{% endif %}
{% endfor %}
与{{ forloop.counter }} 相同,由于循环,它返回多个数字,但我只需要最后一个数字:
{% for question in category.question_set.all %}
{% if not question.solved %}
{{ forloop.counter }} # returns; 1 2 3 4 5 6
{% endif %}
{% endfor %}
我的问题;这可能在模板中还是我需要其他方法?
【问题讨论】:
-
我认为您需要在视图中计算计数并将其返回到寺庙进行显示。
标签: django django-templates django-template-filters