A relationship table records associations between rows in two related tables. It solves the many-to-many problem: a musician can belong to several bands, and a band can contain several musicians. Unlike an ordinary model field, a Django ManyToManyField creates another table rather than another column on the model’s table. section 4.7.2
Think of the database as three connected tables:
- The musician table stores each musician once. section 4.7.2
- The band table stores each band once. section 4.7.2
- The relationship table stores one row for each membership, with its own ID and one key for each related object. section 4.7.2
- Django creates the relationship table when the model defines ManyToManyField; you do not construct it with a ForeignKey field. section 4.7.2
RiffMates memberships
Define the relationship on Band: class Band(models.Model): name = models.CharField(max_length=20); musicians = models.ManyToManyField(Musician). After migrations, create a band with Band.objects.create(name="The Beatles"), find Lennon, and run beatles.musicians.add(lennon). beatles.musicians.all() returns Lennon, while lennon.band_set.all() returns The Beatles. Add several musicians at once with wishful.musicians.add(lennon, vai, bonham). section 4.7.2
Figure 4.10 Database tables for many-to-many relationship between bands and musicians
Inspect the three-table layout to see how band memberships become rows linking musician and band IDs. section 4.7.2
