Aditya Narayan
Aditya Narayan

Reputation: 41

When to use a ManyToMany field over a ForeignKey?

Consider that we have two Django models, Question and Answer. A question can have many answers to it, but an answer can have only one question related to it. We can model the relationship as:

class Question(models.Model):
    text     = models.CharField(...)
    answers  = models.ManyToManyField('Answer')

class Answer(models.Model):
    text     = models.CharField(...)

We can also model it as:

class Question(models.Model):
    text     = models.CharField(...)

class Answer(models.Model):
    text     = models.CharField(...)
    question = models.ForeignKey('Question')

Django managers allow us to follow both ForeignKey and ManyToManyField backwards. What model structure should we use?

Upvotes: 2

Views: 1519

Answers (2)

Manish Pal
Manish Pal

Reputation: 361

class Question(models.Model):
    text     = models.CharField(...)
    answers  = models.ManyToManyField('Answer')

Above models say an Answer can have many Questions and a Question can have many answers. Partially wrong and partially correct.

Many to Many relationships: You have many siblings and your one of a sibling has many siblings.

class Answer(models.Model):
    text     = models.CharField(...)
    question = models.ForeignKey('Question')

Now, this model says an Question can have many Answers and an Answer can have one question only.

One to Many relationships: A person can have many numbers and but a number can't assigned to many persons

In my opinion, it is more correct.

Upvotes: 1

Ali
Ali

Reputation: 3666

one-to-many of course. You could achieve the same thing using many-to-many relationship but you'll complicate things a lot and you'll pay for a performance hit.

Think of it from a database modelling point of view (forget the ORM). Why would you want to do: question -> many-to-many-manager -> answers instead of having: question -> answers.

Upvotes: 2

Related Questions