Django中外键的嵌套循环

qyzbxkaa  于 2023-06-25  发布在  Go
关注(0)|答案(1)|浏览(84)

纽比呼叫 Django 。我需要列出一些音乐流派及其子流派。我得到了流派刚刚好,但我不知道如何列出子流派。
这是我的模型:

class Genre(models.Model):
    genre_id = models.AutoField(primary_key=True)
    code = models.CharField(unique=True, max_length=4)
    description = models.CharField(max_length=25, blank=False, null=False)

    class Meta:
        managed = False
        db_table = 'genre'
        db_table_comment = 'Music genre catalog'

    def __str__(self):
        return self.description

class Subgenre(models.Model):
    subgenre_id = models.AutoField(primary_key=True)
    code = models.CharField(unique=True, max_length=6)
    description = models.CharField(max_length=25, blank=False, null=False)
    genre = models.ForeignKey(Genre, on_delete=models.CASCADE)

    class Meta:
        managed = False
        db_table = 'subgenre'
        db_table_comment = 'Music subgenre catalog'

    def __str__(self):
        return self.description

这是我在www.example.com上找到的views.py:

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

这是我的HTML代码:

{% 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 subgenres.genre.all %}

      <div class="row">
         <label>{{subgenre.description}}</label>
      </div>

      {% endfor %}

   </div>
</div>

{% endfor %}
ijnw1ujt

ijnw1ujt1#

你应该在相反的方向上这样做:

{% 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 %}

作为视图:

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
    )

相关问题