Search code examples
djangoforeign-keysmodels

Can anyone do a many to many relationship between two django models only with the ForeignKey?


I have two Django models, lets say an Album and a Song Model.

I have a ForeignKey field to my Song model so I can correlate multiple songs to an Album (many to one relationship). If I don't change anything in my models and leave them as they are can I succeed a many to many relationship (same song to different albums and vise versa) if I change the way that my database stores my data (normalize, denormalize etc)?

Thanks


Solution

  • No you can't, that's the reason for intermediate tables and the ManyToMany relationship that Django supports.

    In fact, considering that your models are as follows:

    class Song(models.Model):
        album = FK(Album)
    
    class Album(models.Model):
        attributes ...
    

    You have enough representational power to store several songs for one album. You Can't have multiple albums per song.

    Putting the ForeignKey in the Album class would only worsen things, as you can have several albums per song, and each album then belongs to a single song ! (that's definitely wrong right ?)

    So what you want is a ManyToMany relationship, between an Album and a Song, represented like the following:

    class Song(models.Model):
        attributes ...
    
    class Album(models.Model):
        songs = models.ManyToManyField(Song)
    

    This way, each Song belongs to several Albums and vice versa, as you want them to.