【问题标题】:Count booleans inside a for-loop in a django template在 django 模板的 for 循环中计算布尔值
【发布时间】: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


【解决方案1】:

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

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 %}

【讨论】:

  • 感谢您的回答!我做了几乎完全相同的事情来让它工作。而不是 get,我试图覆盖 get_context_data 方法,所以我仍然可以使用 ListView 功能,如 paginate_by 和 ordering,但你的答案肯定有效!
猜你喜欢
  • 2019-05-23
  • 1970-01-01
  • 1970-01-01
  • 2020-01-28
  • 2021-10-17
  • 2012-07-25
  • 2014-09-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多