0

在 Django (2.0) 中,我正在遍历记录以在表格中显示它们,我希望在每条记录的末尾显示一个汇总计数,我有这个使用count = Fraction.objects.all().filter(botany_id=13).count()和显示{{ count }}但是这是为记录 13 设置的,行上的下一条记录有一个 植物学_id=14 那么我该如何动态地执行此操作,本质上是植物学_id=botany_id

#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 }}{{ botany }}给了我植物学 ID

4

1 回答 1

1

使用相关管理器

视图.py

botanies = Botany.objects.all()

模板.html

{% for botany in botanies %}
    {{botany.fraction_set.count}}
{% endfor %}

稍后您需要优化查询数量。

于 2019-02-13T04:48:59.730 回答