Randy Tang
Randy Tang

Reputation: 4353

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?

Upvotes: 4

Views: 2275

Answers (2)

SuperNova
SuperNova

Reputation: 27436

In MySQL level,

Django creates a separate table for the many-to-many Field.

class PaperAuthor(models.Model):
    paper = models.ForeignKey(Paper)
    author = models.ForeignKey(Author)

tablename : app_paperauthor

select * from app_paperauthor;

| id | paper_id | author_id |
| 1  | 1        | 1         |
| 2  | 2        | 2         |

and the many-to-many field creates a table like below.

class Paper(models.Model):
    title = models.CharField(...)
    authors = models.ManyToManyField(Author)

tablename : app_paper_authors

select * from app_paper_authors;

| id | paper_id | author_id   |
| 1  | 1        | 1           |
| 2  | 1        | 2           |

so the difference is the name of the table app_paperauthor and app_paper_authors.

Upvotes: 5

Daniel Roseman
Daniel Roseman

Reputation: 599460

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.

Upvotes: 7

Related Questions