0

我正在使用 Python3 在 Django 3 中的唱片标签网站上工作。(艺术家、发行、轨道结构)

我正在尝试根据当前艺术家页面过滤掉所有曲目的列表。音乐/艺术家/我想在 context_processors 文件中过滤它,但不知道如何,并且无论如何都愿意这样做,如果这是不可能的。

艺术家.html

{% block body %}
<div class="container artistitem">
    <h2>{{ artist.artist_name }}</h2>
    <h3>{{ artist.artist_url }}</h3>
    <h5>{{ artist.artist_id }}</h5>
    <div class="artistimage"><img src="{{ artist.artist_logo.url }}"></div>
    <div>
        <h3>Discography</h3>
        
        <p>
            <ul>
                <!-- for this artist id in all releases print all release name -->
                <!-- {% for release.artist.id in all_releases %}
                    <li>
                        {{ release.release_title }}
                    </li>
                {% endfor %} -->
                <!-- for this artist id in all releases print all release name -->
                {% for track in all_tracks_byartist %}
                <li>
                    {{ track.track_title }}
                </li>
            {% endfor %}
            </ul>
        </p>
    </div>
</div>
{% endblock %}

模型.py

from django.db import models

# Create your models here.
class Artist(models.Model):
    artist_name = models.CharField(max_length=250, default='')
    artist_logo = models.FileField()
    artist_url = models.URLField(blank=True)

    def __str__(self):
        return self.artist_name

class Release(models.Model):
    artist = models.ForeignKey(Artist, on_delete=models.CASCADE, related_name='release')
    release_title = models.CharField(max_length=500)
    release_cover = models.FileField()
    release_duration = models.IntegerField()

    def __str__(self):
        return self.release_title

class Track(models.Model):
    release = models.ForeignKey(Release, default='', on_delete=models.CASCADE)
    artist = models.ForeignKey(Artist, default='', on_delete=models.CASCADE)
    track_title = models.CharField(max_length=200)
    track_version = models.CharField(max_length=200)
    track_genre = models.CharField(max_length=100)
    track_duration = models.IntegerField()
    track_number = models.SmallIntegerField()

    class Meta:
        ordering = ["track_number"]

    def __str__(self):
        return self.track_title

app_name = 'music'

context_processors.py

from music.models import Artist, Release, Track

def all_artists(request):
    artist = Artist.objects.all()
    return {'all_artists':artist}

def all_releases(request):
    release = Release.objects.all()
    return {'all_releases':release}

def all_tracks(request):
    track = Track.objects.all()
    return {'all_tracks':track}

def all_tracks_byartist(request):
    track = Track.objects.all()
    return {'all_tracks_byartist':track}

如果您需要任何其他文件,请告诉我。

4

1 回答 1

1

使用反向关系来获取特定艺术家的曲目。

就像是:

{% for track in artist.track_set.all %}
    <li>
         {{ track.track_title }}
    </li>
{% endfor %}
于 2020-08-09T08:25:28.757 回答