Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: difference between ForeignKey and ManyToManyField

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?

like image 817
Randy Tang Avatar asked Jan 05 '23 19:01

Randy Tang


1 Answers

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.

like image 170
Daniel Roseman Avatar answered Jan 31 '23 00:01

Daniel Roseman