gpt4 book ai didi

django - 访问模板内的foreignKey

转载 作者:行者123 更新时间:2023-12-02 06:31:59 24 4
gpt4 key购买 nike

嗯,这很简单。2个具有ManyToMany关系的模型:

class Artist(models.Model):
name = models.CharField(max_length=100, unique=True)
slug = models.SlugField(max_length=100, unique=True,
help_text='Uniq value for artist page URL, created from name')
birth_name = models.CharField(max_length=100, blank=True)


class Song(models.Model):
title = models.CharField(max_length=255)
slug = models.SlugField(max_length=255, unique=True,
help_text='Unique value for product page URL, create from name.')
youtube_link = models.URLField(blank=False)
artists = models.ManyToManyField(Artist)

我的 View 应该显示最新的 5 首歌曲:

def songs(request, template_name="artists/songs.html"):
song_list = Song.objects.all().order_by('-created_at')[:5]
return render_to_response(template_name, locals(),
context_instance=RequestContext(request))

问题出在模板中...我想显示艺术家姓名但只是不知道该怎么做,我尝试过:

{% for song in song_list %}
{{ artists__name }} - {{ song.title }}
{% endfor %}

非常感谢任何帮助!

最佳答案

尝试将模板代码更改为:

{% for song in song_list %}
{% for artist in song.artists.all %}
{{ artist.name }} - {{ song.title }}
{% endfor %}
{% endfor %}

关于django - 访问模板内的foreignKey,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2055993/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com