Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 77 ยท Models and the ORM

Relationships: ForeignKey, ManyToMany, OneToOne

Connect Django models with ForeignKey, ManyToManyField and OneToOneField, choose the right on_delete rule, use related_name and query across relations.

Real data is rarely a pile of unrelated tables. A book has an author, an article has many tags, a person has exactly one passport. In a relational database these links are stored as columns that hold the primary key of another row. Django wraps that idea in three field types, and it gives you a friendly Python API on both ends of every link.

In this lesson you will declare all three kinds of relationship, decide what should happen to child rows when a parent is deleted, follow links in both directions, attach extra data to a many-to-many link, and filter across relations with double underscores. If you have not defined a model yet, start with Models and Fields. The lessons on queries and lookups explain the filter() syntax used here.

Every example on this page installs Django inside your browser and uses an in-memory SQLite database. The first lines of each example are the same setup block, followed by a small create_tables() helper that builds the tables for you, so you can focus on the models. Pressing Run again is safe: the helper starts from an empty database each time.

The three relationship types

The kind of field you pick depends on how many objects can sit on each side of the link.

erDiagram
    AUTHOR ||--o{ BOOK : "ForeignKey (one to many)"
    BOOK }o--o{ TAG : "ManyToManyField"
    PERSON ||--o| PASSPORT : "OneToOneField"

One author has many books, books and tags link many to many, and a person has at most one passport.

Field Meaning Where the column lives
ForeignKey many rows point to one parent on the "many" side (the child)
ManyToManyField many rows on each side in a separate join table
OneToOneField at most one row on each side on either side (it is a unique foreign key)

You declare the field on one model only. Django adds the matching accessor to the other model for you.

ForeignKey: many to one

A ForeignKey goes on the child model. It needs the parent model (or its name as a string, when the parent is defined later) and an on_delete rule, which is required. The column is stored as <field name>_id, so Book.author is backed by an author_id column.

Python ForeignKey and its reverse accessor

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Look at the three ways the link shows up:

  • kindred.author is the forward accessor. It loads the parent (one query the first time) and returns an Author object.
  • le_guin.books is the reverse accessor. It is a related manager: you can call all(), filter(), count() and create() on it, and anything you create is automatically linked to that author.
  • kindred.review_set shows the default reverse name when you set no related_name: the lower-cased model name plus _set.

Choosing a related_name

Pick a plural, descriptive related_name such as books. It reads better than book_set, and it becomes the name you use in reverse queries (Author.objects.filter(books__title=...)). If you set no related_name, queries use the lower-cased model name instead (review__stars). Two foreign keys from one model to the same parent, such as sender and recipient on a message, must have different related names, otherwise the reverse accessors would clash. A related name of "+" switches the reverse accessor off.

on_delete: what happens to the children?

When you delete a parent row, the database must not be left with children that point at nothing. on_delete tells Django how to handle them. Django applies these rules in Python, before it sends the DELETE, so they work even on databases without cascading foreign keys.

flowchart TD
    A["parent.delete()"] --> B{"on_delete of each child field"}
    B -->|CASCADE| C["delete the children too"]
    B -->|PROTECT| D["raise ProtectedError, delete nothing"]
    B -->|SET_NULL| E["set the column to NULL<br/>(needs null=True)"]
    B -->|SET_DEFAULT| F["set the field default"]
    B -->|DO_NOTHING| G["do nothing: the database decides"]

Django collects every affected row first, and the delete only happens if no rule objects.

Rule Use it when
CASCADE the child makes no sense without the parent (reviews of a book, lines of an order)
PROTECT the parent must not be removed while children exist (customers with invoices)
RESTRICT like PROTECT, but allows the delete if the same row is also removed through a cascade from another path
SET_NULL the child should survive, with the link cleared (needs null=True)
SET_DEFAULT the child should fall back to the field's default
SET(value_or_callable) the child should point at a replacement, such as a "deleted user" placeholder
DO_NOTHING you handle it yourself, for example with a database-level rule. A foreign key constraint may then raise IntegrityError

The next example sets up one parent with a child of each of the three most common kinds.

Python CASCADE, PROTECT and SET_NULL in action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

delete() returns the total number of rows removed and a dictionary with one count per model, which is a handy way to see what a cascade touched. Notice that the protected order stopped the whole operation: no review was deleted by the failed attempt.

Warning: CASCADE is convenient and dangerous. Deleting one Author can silently remove thousands of rows through a chain of cascades. For business records such as orders and invoices, prefer PROTECT or a "soft delete" flag, and keep CASCADE for data that is truly owned by the parent.

ManyToManyField

When both sides can have many partners, use ManyToManyField on either model (put it where it reads most naturally, and do not declare it on both). Django creates a hidden join table with two foreign keys. You never touch that table directly; you use a related manager on both ends instead.

Python Adding and removing many-to-many links

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The manager methods you will use most:

  • add(*objects) links objects; adding a link that already exists changes nothing.
  • remove(*objects) unlinks them. clear() unlinks everything.
  • set(objects) makes the relation match the list exactly, adding and removing as needed.
  • create(...) makes a new related object and links it in one step.

Changes to a many-to-many relation are written immediately; there is no need to call save(). The object must already be saved, because the link rows need its primary key.

Extra data with a through model

Sometimes the link itself has facts: when a student enrolled, which grade they got, how many of a product are in an order. Create a model for the link and name it in through=. It needs a ForeignKey to each side, and you can add any other fields.

erDiagram
    STUDENT ||--o{ ENROLLMENT : has
    COURSE ||--o{ ENROLLMENT : has
    ENROLLMENT {
        string grade
    }

The explicit join model Enrollment carries the grade; Student and Course are linked through it.

Python A through model with a grade

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

With a through model, add() still works, but any required extra fields must be passed as through_defaults. You can also create Enrollment rows directly, which is often clearer. A UniqueConstraint on the two foreign keys keeps a student from enrolling twice. If you think you may ever need extra data on a link, start with a through model: adding one later to a live ManyToManyField is a painful migration.

OneToOneField

A OneToOneField is a foreign key with a unique constraint. It is the right tool for splitting one concept across two tables, for instance a core User plus an optional Profile, or for multi-table inheritance. The reverse side is a single object rather than a manager, so person.passport returns the passport itself.

If no row exists on the other side, accessing the reverse attribute raises Passport.DoesNotExist (technically a RelatedObjectDoesNotExist, which subclasses it). Catch that exception, or use a try/except, rather than testing for None.

Joining across relations in lookups

The double underscore also walks through relations, so you can filter on a parent's field from the child, or the other way round. Django writes the SQL JOIN for you.

Python OneToOne plus lookups across relations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Remember three things about relation lookups:

  • Forward lookups use the field name (person__name). Reverse lookups use the related_name, or the lower-cased model name if there is none (trip__city).
  • A reverse join returns the parent once for every matching child, so filter(trip__city="Oslo") listed Ines twice. Add .distinct() when you need each parent once. The aggregation lesson shows the counting alternative.
  • __isnull=True on a reverse relation is the idiomatic way to find parents that have no children. You can chain as many hops as you need (person__passport__country).

Walking a relation inside Python code (trip.person.name in a loop) is a different matter: each hop can trigger a new query. The lesson on ORM performance shows how to load related rows efficiently.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which model gets the ForeignKey for 'one Author has many Books'?

    The foreign key column lives on the 'many' side. Book.author stores the author's id, and Django adds author.book_set (or your related_name) to Author automatically.
  2. 2. A customer has invoices that must never disappear by accident. Which on_delete rule fits best?

    PROTECT raises ProtectedError and deletes nothing while invoices exist. CASCADE would remove the invoices, and SET_NULL would leave orphaned invoices with no customer.
  3. 3. How do you store a grade for each student-course pair in a many-to-many relation?

    Only an explicit through model can hold extra columns. Django's automatic join table has just the two foreign keys.
  4. 4. Author.objects.filter(books__title__startswith='The') returns the same author three times. What fixes it?

    A reverse join produces one row per matching child, so the parent repeats. distinct() collapses duplicates.

Summary

  • ForeignKey lives on the child model, requires on_delete, and is stored as an <name>_id column.
  • The parent gets a reverse manager: related_name if you set one, otherwise <model>_set.
  • Choose on_delete deliberately: CASCADE for owned data, PROTECT or RESTRICT for records you must keep, SET_NULL for optional links.
  • ManyToManyField creates a hidden join table; use add, remove, set and clear, and no save() is needed.
  • Use through= when the link carries its own data, and pass through_defaults to add().
  • OneToOneField is a unique foreign key whose reverse side returns one object or raises DoesNotExist.
  • Double underscores follow relations in both directions; use distinct() for repeated parents and __isnull=True to find childless ones.

Next, learn to count, sum and group related rows in Aggregation and Annotation.