TExcelTAD
Home › Django › Django ForeignKey

Django ForeignKey

Real data is connected: a book has an author, an order belongs to a customer, a comment belongs to a post. In a relational database, these one-to-many links are stored as a column holding the primary key of another table — a foreign key. In Django you declare it with models.ForeignKey.

python
class Author(models.Model):
    name = models.CharField(max_length=50)

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name="books")

One author → many books; each book → exactly one author. The ForeignKey lives on the "many" side.

Argument Meaning
first argument the related model (class or "app_label.Model" string)
on_delete what happens when the author is deleted — required (see Delete Data)
related_name name of the reverse accessor on Author (default: book_set)
null=True, blank=True make the relation optional

Note: Examples in this lesson install a stand-in demo app, because Django only builds reverse relations (author.books) for installed apps — see How the Playground Runs Django.

Creating related objects and following links

python · try it yourself
import sys, types, django
from django.conf import settings
sys.modules["demo"] = types.ModuleType("demo")      # stand-in for a demo/ app package
sys.modules["demo"].__file__ = "demo/__init__.py"
settings.configure(INSTALLED_APPS=["demo"],
                   DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}})
django.setup()
from django.db import models, connection

class Author(models.Model):
    name = models.CharField(max_length=50)
    class Meta:
        app_label = "demo"
    def __str__(self):
        return self.name

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name="books")
    class Meta:
        app_label = "demo"
    def __str__(self):
        return self.title

with connection.schema_editor() as editor:
    editor.create_model(Author)
    editor.create_model(Book)

tolkien = Author.objects.create(name="Tolkien")
book = Book.objects.create(title="The Hobbit", author=tolkien)
Book.objects.create(title="The Silmarillion", author_id=tolkien.id)   # by id also works

print(book.author, "| author_id column:", book.author_id)       # forward: book -> author
print(list(tolkien.books.order_by("title")))                     # reverse: author -> books
print(tolkien.books.count())

tolkien.books.create(title="Unfinished Tales")                   # create through the relation
print([b.title for b in tolkien.books.order_by("id")])
Tolkien | author_id column: 1
[<Book: The Hobbit>, <Book: The Silmarillion>]
2
['The Hobbit', 'The Silmarillion', 'Unfinished Tales']
Expression Direction Returns
book.author forward an Author object
book.author_id forward the raw key value (no query)
author.books (or author.book_set) reverse a related manager — use .all(), .filter(), .count(), .create()

Querying across relationships

Double underscores follow relationships inside lookups, in both directions. Django writes the JOIN for you:

python · try it yourself
import sys, types, django
from django.conf import settings
sys.modules["demo"] = types.ModuleType("demo")
sys.modules["demo"].__file__ = "demo/__init__.py"
settings.configure(INSTALLED_APPS=["demo"],
                   DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}})
django.setup()
from django.db import models, connection

class Author(models.Model):
    name = models.CharField(max_length=50)
    country = models.CharField(max_length=30)
    class Meta:
        app_label = "demo"

class Book(models.Model):
    title = models.CharField(max_length=100)
    year = models.IntegerField()
    author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name="books")
    class Meta:
        app_label = "demo"

with connection.schema_editor() as editor:
    editor.create_model(Author)
    editor.create_model(Book)

murakami = Author.objects.create(name="Murakami", country="Japan")
austen = Author.objects.create(name="Austen", country="UK")
ishiguro = Author.objects.create(name="Ishiguro", country="UK")
for title, year, a in [("Norwegian Wood", 1987, murakami), ("1Q84", 2009, murakami),
                       ("Emma", 1815, austen), ("Klara and the Sun", 2021, ishiguro)]:
    Book.objects.create(title=title, year=year, author=a)

uk_books = Book.objects.filter(author__country="UK").order_by("year")
print([b.title for b in uk_books])

recent_authors = Author.objects.filter(books__year__gte=2000).order_by("name")
print([a.name for a in recent_authors])

print(list(Book.objects.order_by("author__name", "title").values_list("author__name", "title")))
['Emma', 'Klara and the Sun']
['Ishiguro', 'Murakami']
[('Austen', 'Emma'), ('Ishiguro', 'Klara and the Sun'), ('Murakami', '1Q84'), ('Murakami', 'Norwegian Wood')]

books__year__gte goes from Author backwards to Book using the related_name. If you filter across a reverse relation and several related rows match, the parent can appear multiple times — add .distinct() when that matters.

The N+1 problem and select_related()

Accessing book.author runs a query the first time for each book. Looping over 100 books would mean 1 + 100 queries — the infamous N+1 problem. select_related() fetches the related rows in the same query with a SQL JOIN; prefetch_related() does one extra query for reverse/many relations:

python · try it yourself
import sys, types, django
from django.conf import settings
sys.modules["demo"] = types.ModuleType("demo")
sys.modules["demo"].__file__ = "demo/__init__.py"
settings.configure(INSTALLED_APPS=["demo"],
                   DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}})
django.setup()
from django.db import models, connection
from django.test.utils import CaptureQueriesContext

class Author(models.Model):
    name = models.CharField(max_length=50)
    class Meta:
        app_label = "demo"

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name="books")
    class Meta:
        app_label = "demo"

with connection.schema_editor() as editor:
    editor.create_model(Author)
    editor.create_model(Book)
for i in range(1, 5):
    a = Author.objects.create(name=f"Author {i}")
    Book.objects.create(title=f"Book {i}a", author=a)
    Book.objects.create(title=f"Book {i}b", author=a)

with CaptureQueriesContext(connection) as ctx:
    lines = [f"{b.title} by {b.author.name}" for b in Book.objects.order_by("id")]
print("naive loop:      ", len(ctx.captured_queries), "queries")

with CaptureQueriesContext(connection) as ctx:
    lines = [f"{b.title} by {b.author.name}" for b in Book.objects.select_related("author").order_by("id")]
print("select_related:  ", len(ctx.captured_queries), "query")

with CaptureQueriesContext(connection) as ctx:
    summary = {a.name: [b.title for b in a.books.all()] for a in Author.objects.prefetch_related("books").order_by("id")}
print("prefetch_related:", len(ctx.captured_queries), "queries")
print(lines[0], "|", summary["Author 4"])
naive loop:       9 queries
select_related:   1 query
prefetch_related: 2 queries
Book 1a by Author 1 | ['Book 4a', 'Book 4b']

Tip: Use select_related() for forward ForeignKey/OneToOneField access, and prefetch_related() for reverse relations and many-to-many. Both are among the biggest performance wins in Django.

OneToOneField

A OneToOneField is a foreign key with a unique constraint: each row on one side matches at most one row on the other. A classic use is extending the user model with a profile:

python
from django.conf import settings

class Profile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    bio = models.TextField(blank=True)

# profile.user  -> the User;   user.profile -> the Profile (a single object, not a manager)

Test yourself

On which model do you put the ForeignKey in an Author–Book (one-to-many) relationship?

  1. Author
  2. Book
  3. Both
  4. A third model

With related_name="books", how do you get all books of author?

  1. author.book
  2. author.books.all()
  3. Book.author.all()
  4. author.book_set

Which method avoids one extra query per book when printing book.author.name in a loop?

  1. only()
  2. select_related("author")
  3. distinct()
  4. values()