I seem to have confusion about Django's ForeignKey and ManyToManyField. Supposing I have the following two models:
class Author(models.Model):
name = models.CharField(...)
class Paper(models.Model):
title = models.CharField(...)
A paper may have several authors. I may do either of the followings:
a) Add an authors
field in Paper
and add authors to a Paper
instance:
authors = models.ManyToManyFields(Author)
b) Or, I can create another model which contains the authors of a paper:
class PaperAuthor(models.Model):
paper = models.ForeignKey(Paper)
author = models.ForeignKey(Author)
Which of the above two is correct?
Those are exactly equivalent. A ManyToManyField automatically creates that "through" table for you; the only difference is that it gives you the ability to access all authors for a paper, or all papers for an author, with a single expression.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With