liveBook · Manning

Relationship table

As explained in Django in Action

A relationship table is an intermediate database table that records associations between rows in two related tables.

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
figure

Inspect the three-table layout to see how band memberships become rows linking musician and band IDs. section 4.7.2

How Django in Action covers it

How deep it goes
Defines the table’s columns and Django’s automatic creation, then demonstrates adding and querying memberships.
Examples
Uses RiffMates bands and musicians, including Beatles memberships and a band with Lennon, Vai, and Bonham.
What it assumes
Assumes basic Django models and migrations while distinguishing many-to-many associations from one-way foreign-key relationships.
What you can do after
Operate relationships via Django ORM methods such as add() and all().
How it connects
Links many-to-many relationships, foreign keys, models, migrations, and Django ORM queries.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Django in Action. The section links point to the parts of the book it draws on.