I haven’t taken any database course. Please excuse me…
From Django Book tutorial, we have a book application which has three classes initially (Book, Publisher and Author).
class Book(models.Model):
title = models.CharField(max_length=100)
# categories = models.ManyToManyField(Category)
authors = models.ManyToManyField(Author)
publisher = models.ForeignKey(Publisher)
publication = models.DateField()
We can match a book to many authors while we can match only a book to a Publisher.
A book can have several categories so it seems natural to write what I’ve commented out above.
class Category(models.Model):
name = models.CharField(max_length=40)
Second attempt:
I remember reading this somewhere (vaugly): create BookCategories which takes Category as ForeignKey.
Book --> --> BookCategories --> Categroy
(Notation: double arrows = ManyToMany and single arrow = ForeginKey)
Which one is better? If none, how do I approach this? Where is my logic flaw? If the second attempt is better, what is the reason?
Thank you very much.
I believe the approaches you have described are more or less identical. A many-to-many field always requires an interstitial or ‘through’ table to store the links between the two object types.
In the first approach you’ve described, Django will create the through table automatically when you run syncdb. In the second approach you’ve just defined that table manually (although as you’ve specified it you would have a redundant table). The second approach is useful in some circumstances, because it means you can not only define a link, but also store information about that link. In this case, you might have a field that stores the time when a book was first added to a category, or the user that added it.
For more information, check out the Django docs on many-to-many through tables.