[Answered ]-Using Foreign Key value in if condition in Django Template

1👍

You can access the related Charts 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 Charts 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 Categorys, and N queries to fetch each time the related chart_set of a category.

Leave a comment