Skip to content
Advertisement

Querying One model item from another model

I have a list of Artist (Musicians) and their Albums they created. T

My models looks like the following:

from django.db import models

# Create your models here.
class ArtistModel(models.Model):
    Artist_name = models.CharField(max_length=50, null=True, default=False)
    
    def __str__(self):
        
        return self.Artist_name
    
class AlbumsModel(models.Model):
    
    Genre = {
        ('Hip-Hop','Hip-Hop'),
        ('Rnb','Rnb'),
        ('Rock n Roll','Rock n Roll'),
        ('House','Housep'),
        ('Gospel','Gospel'),
        ('Classical','Classical'),
    }
    
    Album_name = models.CharField(max_length=50, null=True, default=False)  
    Album_by = models.ForeignKey(ArtistModel ,max_length=50, null=True, default=False, on_delete=models.CASCADE)      
    Music_genre = models.CharField(max_length=50, null=True, default=False, choices=Genre)    
    
    def __str__(self):
        return self.Album_name

My Views

from django.shortcuts import render
from . models import AlbumsModel, ArtistModel

# Create your views here.
def Albums(request):
    AllAlbums = AlbumsModel.objects.all()
    return render(request, 'Albums/Home.html',
                  {'AllAlbums':AllAlbums})


def Artist(request):
    AllArtist = ArtistModel.objects.all()
    return render(request, 'Albums/Artist.html',
                  {'AllArtist':AllArtist})

My HTML is the following:

{% extends 'Albums/Layout.html' %}

{% block content %}
<h1>Artist</h1>
<br/>
{% for artistview in AllArtist %}
<a href="{% url 'Artist_album' %}">
    {{artistview}}<br>
</a>
{% endfor %}
{% endblock %}

My shell looks like the following:

In [24]: All_Albums
Out[24]: <QuerySet [<AlbumsModel: THE EMINEM SHOW>, <AlbumsModel: THE MARSHELL MATHERS LP>, <AlbumsModel: BLUEPRINT>, <AlbumsModel: THE BLACK ALBUM>, <AlbumsModel: 4:44>, <AlbumsModel: MAGNA CARTA HOLY GRAIL>, <AlbumsModel: JESUS IS KING>, <AlbumsModel: DONDA>, <AlbumsModel: GRADUATION>]>

In [25]: Artist_all
Out[25]: <QuerySet [<ArtistModel: Eminem>, <ArtistModel: Jayz>, <ArtistModel: Kanye West>]>

I would like to learn how to select One artist “Eminem” and have all albums associated with his model listed on the next page.

So i would select “Jayz”, and be directed to another page with all of his albums “BLUEPRINT, THE BLACK ALBUM, 4:44”

Advertisement

Answer

Use the reverse accessor like this:

artist_model = ArtistModel.objects.get(Artist_name="Eminem")
eminem_albums = artist_model.albumsmodel_set.all()

And in your template:

{% for album in artist_model.albumsmodel_set.all %}
    {{ album }}
{% endfor %}

Two tips on naming conventions:

  1. Django models should be PascalCase but not have the word ‘Model’ in them, unless this helps the description somehow.
  2. Functions (including views), model fields, and variables should be in snake_case
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement