计算 django 模板中 for 循环内的布尔值

Count booleans inside a for-loop in a django template

我想知道如何计算我的 Django 模板中 for 循环内的所有 true/false 布尔值,但我不确定如何在循环内实现这一点。我的目标是向用户展示有多少问题 unsolved/solved.

假设这些是我的模型:

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 }}
但是我不能在循环中这样做,因为它 returns: 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 }} 相同,它 returns 由于循环而有多个数字,但我只需要最后一个数字:

{% for question in category.question_set.all %} 
    {% if not question.solved %}
        {{ forloop.counter }} # returns; 1 2 3 4 5 6
    {% endif %}
{% endfor %}

我的问题;这可能在模板内还是我需要另一种方法?

在视图中计算比在模板中计算更好:

class CategoryView(ListView):
    model = Category

    def get(self, request, *args, **kwargs):
        categories = []
        for category in self.get_queryset():
            questions = category.question_set.all()
            count = sum([q.solved for q in questions])
            categories.append([questions, count])
        return render(request, 'TEMPLATE NAME HERE', {'categories': categories})

现在在模板中,您可以遍历每个类别,还可以访问已解决的计数:

{% for questions, solved_count in categories %} 
    {# display solved count and then loop through questions #}
{% endfor %}