在Django(2.0)中,我正在遍历记录以在表中显示它们,我希望在每条记录的末尾显示一个汇总计数,我使用count = Fraction.objects.all().filter(botany_id=13).count()
进行了此工作,而显示{ {1}}但这是为记录13设置的,该行的下一个记录具有植物学ID = 14,所以我该如何动态地执行此操作,本质上是植物学ID = botany_id
{{ count }}
#views.py
def allflotation(request):
botany = Botany.objects.all()
fraction = Fraction.objects.all()
count = Fraction.objects.all().filter(botany_id=13).count()
fractioncomposition = FractionComposition.objects.all()
# fractionmaterialspresent = FractionMaterialsPresent.objects.all()
return render(request, 'flotation/allflotation.html',
{
'botany':botany,
'fraction':fraction,
'count':count,
'fractioncomposition':fractioncomposition,
# 'fractionmaterialspresent':fractionmaterialspresent
})
将#html
...
<tbody>
{% for botany in botany.all %}
<tr>
<td>{{ botany.sample_id }}</td>
<td>{{ botany.area_easting }}.{{ botany.area_northing }}.{{ botany.context_number }}</td>
<td>{{ botany.botany_id }}</td>
<td>{{ botany.sample_number }}</td>
<td>{{ botany.entry_date }}</td>
<td>{{ botany.flotation_date }}</td>
<td>{{ botany.analyst }}</td>
<td>{{ botany.notes }}</td>
<td>
<div class="btn-group" role="group" aria-label="Basic example">
<a href="{% url 'addfraction' pk=botany.botany_id %}">
<span class="badge badge-primary">
Add Fraction
<br />
<span class="badge badge-light">
{{ count }}
</span>
</span>
</a>
...
更改为{{ count }}
给我的植物学编号
答案 0 :(得分:1)
views.py
botanies = Botany.objects.all()
template.html
{% for botany in botanies %}
{{botany.fraction_set.count}}
{% endfor %}
您稍后需要优化查询数量。