Sourajit Mohanty
Sourajit Mohanty

Reputation: 1

How to access the id of the Primary class in the foreign class in django?

I have 2 model classes(Album and Songs) where Song is d foreign class. I want to access the id of the Album class in the Song class. How can i do that??

class Album(models.Model):
   artist=models.CharField(max_length=250)
   title=models.CharField(max_length=500)

class Song(models.Model):
   album=models.ForeignKey(Album,on_delete=models.CASCADE)
   song_title=models.CharField(max_length=250)

   def get_absolute_url(self):
   //I need to access the Album ID from here..so that i can 
   redirect myself to the Album's url after adding a new song

Upvotes: 0

Views: 54

Answers (2)

Usama Nadeem
Usama Nadeem

Reputation: 128

Above is the correct code. But, you don't need an extra field of id in both classes. That is why, Django already created this type of field in DB.

class Album(models.Model):
    album_name = models.CharField(max_length=100)
    def __str__(self):
        return self.album_name
class Song(models.Model):
    song_name = models.CharField(max_length=100)
    album = models.ForeignKey(Album, related_name='songs', on_delete='CASCADE')
    def __str__(self):
        return self.song_name

Upvotes: 0

rchurch4
rchurch4

Reputation: 899

Welcome to StackOverflow! So, what I assume your code here looks like is something like:

class Album(models.Model):
    id = models.IntegerField()
    album_name = models.CharField(max_length=100)

class Song(models.Model):
    id = models.IntegerField()
    song_name = models.CharField(max_length=100)
    album = models.ForeignKey(Album, related_name='songs')

Lets say you've gotten a song record by doing song = Song.objects.get(id=x). Then you would get the album id by the following: song.album.id

Upvotes: 2

Related Questions