scottc11
scottc11

Reputation: 916

Django - how do you decide which model to put foreign key?

Lets say I have two models that looks like this:

class Album(models.Model):
    pub_date = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=250, blank=False, unique_for_date="pub_date")


class Track(models.Model):
    title = models.CharField(max_length=250, blank=False, unique_for_date="pub_date")
    album = models.ForeignKey(Album)

What is the difference between putting the ForeignKey (one-to-many) relationship on the Track model versus having a many-to-many on the Album model?

How does one decide such a thing?

Upvotes: 1

Views: 287

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599450

Those would do completely different things.

Like you said, a ForeignKey is a one-to-many relationship. If you put it on Track, that means that many tracks belong to one album (or in other words, one album has many tracks). If you put it on Album, that means that many albums belong to one track, which is clearly not right.

The situation where there is a choice is when you're using a ManyToManyField. There, both sides are "many", so the choice of which side to put the field on is a purely semantic one.

Edit Again, these have different effects. A many-to-many would mean that both sides can have multiple items: an album can have many tracks and a track can belong to many albums.

Upvotes: 1

Related Questions