pynovice
pynovice

Reputation: 7752

What is the difference between placing ForeignKey on which models in Django?

I know this is a very basic question. Let's say I have two models:

class Quiz(models.Model):

    name = models.CharField(max_length=100)
    description = models.TextField()

class Question(models.Model):

    quiz = models.ForeignKey(Quiz)
    name = models.CharField(max_length=100)

Here, one quiz can consist of many questions and one question belongs to only one quiz. That's why ForeignKey relation makes sense. But instead of that I could have done like this:

class Question(models.Model):

    name = models.CharField(max_length=100)
    description = models.TextField()

class Quiz(models.Model):

    question = models.ForeignKey(Question)
    name = models.CharField(max_length=100)

What's the difference? And, how do I determine on which model should I put the ForeignKey. Thanks

Upvotes: 0

Views: 80

Answers (3)

Harshit Agarwal
Harshit Agarwal

Reputation: 908

Foreign Key is simply a OnetoMany Field.

so for the first snippet i.e.

class Quiz(models.Model):

    name = models.CharField(max_length=100)
    description = models.TextField()

class Question(models.Model):
    quiz = models.ForeignKey(Quiz)
    name = models.CharField(max_length=100)

you can tag a Quiz with one question. but in 2nd snippet i.e.

class Question(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField()

class Quiz(models.Model):
    question = models.ForeignKey(Question)
    name = models.CharField(max_length=100)

you can tag one question to many Quiz.

your requirement is "one quiz can consist of many questions" so you should do it using the first snippet.

if you do it using the 2nd snippet then one question relates to many Quiz which you don't want to do.

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599450

You say this yourself. In your first snippet, a Question belongs to one Quiz, and a Quiz has many Questions. But if you move it to the other model, the relationships also change: now a Question belongs to many Quizzes, and a Quiz has only one Question. So it depends which model you want to make the "many" side of the one-to-many relationship: the one that has the ForeignKey field is the one that is the "many".

Upvotes: 1

Nafiul Islam
Nafiul Islam

Reputation: 82440

Its really about ownership. You need to ask yourself, who owns what fields, or this is at least how I think about this.

In your first example, the Question belongs to the Quiz model, but in the second one, the Quiz Model is owned by the Question object.

So, this is the simple question one should be asking oneself, does a question belong to many quizzes or does a quiz have many questions? Since Quiz is the one that has many questions, you should use the first one.

Check the documentation on ForeignKey.

Upvotes: 1

Related Questions