[Answered ]-Nested loop for foreign key in Django

1👍

You should do this in the opposite direction:

{% for genre in genres %}
<div class="card">
   <div class="card-header">
      <h5 class="mb-0">{{ genre.description }}</h5>
   </div>
   <div class="card-body">
      {% for subgenre in genre.subgenre_set.all %}
      <div class="row">
         <label>{{ subgenre.description }}</label>
      </div>
      {% endfor %}
   </div>
</div>
{% endfor %}

and as view:

def new_playlist(request):
    genres = Genre.objects.prefetch_related('subgenre_set').order_by(
        'description'
    )
    context = {'genres': genres}
    return render(
        request, 'applications/ecommerce/playlists/new-playlist.html', context
    )

Leave a comment