我想知道如何在我的 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 %}
我的問題; 這可能在模板中還是我需要另一種方法?
uj5u.com熱心網友回復:
在視圖中計算它比在模板中計算更好:
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 %}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/416247.html
標籤:
