我有一个for循环内部的另一个for循环,我试图从内部循环获得索引(forloop.counter)。由于某些原因,Django只给了我外部索引。
{% for category in categories %}
{% for product in products %}
{% if product.category.name == category.name %}
<p>This is the amount of products inside this category: {{ forloop.counter }}<p>
{% endif %}
{% endfor %}
{% endfor %}
可以使用forloop。来进入外部的forloop,所以在这个例子中{{forloop. Parentloop .counter}}。{{forloop。Counter}}已经给出了内部循环。
返回到类别视图(例如在views.py中)并添加注释:
from django.db.models import Count
categories = Category.objects.annotate(num_products=Count('product'))
记住在这个视图的上下文中包含注释:
context.update({'categories': categories})
return render(request, 'myapp/categories.html', context)
现在,调整模板以显示计数:
{% for category in categories %}
<p>This is the amount of products inside this category: {{ category.num_products }}<p>
{% endfor %}