liveBook · Manning

Foreign key

As explained in Django in Action

A foreign key relationship is a database relationship in which records in one table reference a record in another table through a foreign key.

A foreign key connects a row in one database table to a row in another by storing the related row’s ID. In Django, a ForeignKey model field creates that relationship column. section 4.7 section 4.7.2

Use the relationship shape to choose the database design:

  • One-to-many: one venue can have multiple rooms, while each room belongs to one venue. section 4.7
  • Many-to-many: use a separate relationship table containing foreign keys to both participating tables, rather than one ForeignKey column. section 4.7 section 4.7.2
  • Django provides ForeignKey for one-way relationships and ManyToManyField for relationships that work in both directions. section 4.7 section 4.7.2

Rooms belonging to venues

Model a venue-to-room relationship with a ForeignKey on Room. The database stores the venue ID on each room row, allowing several rooms to reference one venue while keeping each room associated with a single venue. section 4.7

Figure 4.9 One-to-many vs. many-to-many relationships
figure

Compare one-to-many foreign-key relationships with many-to-many relationships before choosing a Django model field. section 4.7

How Django in Action covers it

How deep it goes
Defines stored IDs and contrasts one-to-many with relationship-table many-to-many designs, without detailing migrations or query code.
Examples
Uses venues and rooms for one-to-many relationships, and musicians and bands for many-to-many relationships.
What it assumes
Defines database tables and related-row IDs while introducing relationship cardinality through concrete venue, room, musician, and band examples.
What you can do after
Apply it via Django ORM by distinguishing ForeignKey columns from ManyToManyField relationship tables.
How it connects
Connects database tables, record IDs, one-to-many relationships, many-to-many relationships, ForeignKey, and ManyToManyField.

Also explained in

Compare how 18 books explain foreign key →

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.