Search code examples
pythondjangodjango-modelsdjango-rest-frameworkdjango-views

How to interact between Models inside model.py?


There is something I want to do but I don't know how to do it. in this case I have 2 Models in project named 1.Music 2.Artist

1. Music Model is saving music details such as musicName,artistName,genre,etc...
2. Artist Model has only one job and that is saving Artist names.

I want to write a code for my models to when I'm adding a new music in admin panel, Music Model checks the Artist Model for existence artist names and if artist name existed => just add music details and if artist name not existed Then add a new artist in Artist Model.

This is my sample model.py code:

class Artist(models.Model):
    name = models.CharField(max_length=100)


class Music(models.Model):
    name = models.CharField(max_length=100)
    artist = models.CharField(max_length=100)
    genre = models.CharField(max_length=100)

Solution

  • You can use ForeignKey in artist field instead of CharField. So, your Music model will look like this:

    class Music(models.Model):
        name = models.CharField(max_length=100)
        artist = models.ForeignKey(Artist, null=True, on_delete=models.SET_NULL)
        genre = models.CharField(max_length=100)
    

    When you want to get musics by spesific artist in views.py, use filter():

    musics = Music.objects.filter(artist=1)