Access foreignKey inside the template

Well, it's quiet. 2 models with ManyToMany ratio:

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)

In my view, it is supposed to show the last 5 songs:

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))

and the problem is in the template ... I want to display the artist name but just don’t know how to do it, I tried:

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

would appreciate any help!

+3
source share
2 answers

Try changing the template code to:

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

artistsis a different type of manager, so you need to iterate through artists.alland print the attribute namefor each element.

+1
source

Source: https://habr.com/ru/post/1728284/


All Articles