[Answered ]-For loop in template django with prefetch_related

1👍

The reason this does not work is because of the use of .values(…) [Django-doc]. Furthermore you did not specify a related_name=… parameter [Django-doc], so that means that you access the reports with .report_set.all():

contract = testimport.objects.filter(
    so_hd__in=get_user, so_hd=so_hd
).order_by('id').prefetch_related()  # no .values()
context = {
    'contract': contract,
    'the_next': the_next,
    'the_prev': the_prev,
    'so_hd': so_hd,
    'form': form,
    'form1':form1
}
return render(request, 'caller_template/contract_detail.html', context)

and in the template render with .report_set.all:

{% for report in contract %}
   {% for content in report.report_set.all %}
        <tr>
             <td>{{ forloop.counter }}</td>
             <td>{{ content.noi_dung }}</td>
        </tr>
    {% endfor %}
 {% endfor %}

Leave a comment