在forloop之后,根据模板django中的条件获取递增计数

时间:2019-01-15 04:45:13

标签: python django

编辑:这是我的view.py代码和渲染这些列表的模板,因此我如何根据部门列表中的部门ID获取该计数

view.py

def settings(request):
campuses = Campus.objects.all()
faculties = Faculty.objects.all()
departments = Department.objects.all()
programmes = Programme.objects.all()
# programme_by_department = programmes.select_related('department')
# department = Department.objects.get(pk=id)
programme_in_department = Programme.objects.values('department_id')


return render(request, 'settings.html', {'my_campus_list': campuses,
                                         'my_faculty_list': faculties,
                                         'my_department_list': departments,
                                         'my_programme_list': programmes,
                                         'programme_by_department': programme_in_department})

department_list.html

{% for my_programme in my_programme_list %}
<tr>
<td>
{{ forloop.counter }}
</td>
<td><small>{{ my_programme.programme_name }}</small></td>
<td><small>{{ my_programme.programme_type }}</small></td>
<td><small>{{ my_programme.department.department_name }}</small></td>

<td>

    <a href="#" onclick="return false;" type="button" class="js-update-programme"  data-url="{% url 'programme_update' my_programme.id %}"><i class="fa fa-pencil-square-o"></i></a>

    <a href="#" onclick="return false;" type="button" class="js-programme-delete" data-target="#modal-programme" data-url="{% url 'programme_delete' programme_id=my_programme.id %}"><i class="fa fa-trash"></i></a>

</td>
</tr>
 {% empty %}
    <tr>
      <td colspan="7" class="text-center bg-warning">No Programmes</td>
    </tr>



{% endfor %}

1 个答案:

答案 0 :(得分:0)

我建议您在{% if my_programme_by_department.department_id == my_department.id %}本身中进行view.py,然后将最终查询集发送到前端。您还可以将查询集的length打包到上下文中并发送它。或者,您可以使用.count方法在前端获取计数。

views.py

中的
new_set = [ my_programme_by_department for my_programme_by_department in programme_by_department if  my_programme_by_department.department_id == my_department.id ]

new_set_length = len(new_set)

现在您可以在上下文中打包这两个

context = {
'new_set':new_set,
'new_set_length':new_set_length 
}

只需使用{{ new_set_length }}

在前端照常渲染

最好将大多数逻辑留给views.py而不是将它们带到模板中。