1👍
✅
Enumerate over the queryset:
{% for section_leaders in names.section_leader.all %}<h5>
Section Leader -- <a href="{% url 'section_leader_date' section_leaders.id %}">{{ section_leaders }}</a>
-- Total -- {{ section_leaders.section_meeting_date.count }} --
{% for meeting in section_leaders.section_meeting_date.all %} {{ meeting }} {% endfor %}
</h5>{% endfor %}
I would furthermore advice to prefetch the section_leader
s and their section_meeting_date
s to prevent N+1 problems:
from django.shortcuts import get_object_or_404
def cost_center_id(request, pk):
# provides the name of the section leaders for each cost center ID
names = get_object_or_404(
CostCenterID.objects.prefetch_related(
'section_leader__section_meeting_date'
),
pk=pk,
)
context = {
'names': names,
}
return render(request, 'DeptSummary/cost_center_id.html', context)
Note: It is often better to use
get_object_or_404(…)
[Django-doc],
then to use.get(…)
[Django-doc] directly. In case the object does not exists,
for example because the user altered the URL themselves, theget_object_or_404(…)
will result in returning a HTTP 404 Not Found response, whereas using
.get(…)
will result in a HTTP 500 Server Error.
Source:stackexchange.com