1👍
✅
You can access the related Chart
s of a Category
object with my_category.chart_set
, so you implement this with:
def drawcharthome(request):
allcats = Category.objects.prefetch_related('chart_set')
return render(request, 'charts/drawcharthome.html',{'allcats':allcats})
and render this in the template with:
{% for cat in allcats %}
{% for chart in cat.chart_set.all %}
<li>
<a href="{{ chart.api_url }}"> {{ chart.titleFA }}</a>
</li>
{% endfor %}
{% endfor %}
The .prefetch_related(…)
[Django-doc] is not necessary, but it will load all the related Chart
s with a single query and do the joining in the Django/Python layer, which will result in two queries instead of N+1 where you make one query to fetch the Category
s, and N queries to fetch each time the related chart_set
of a category.
Source:stackexchange.com