← Back to Django Course | Chapter 6: Advanced ORM Queries | Lesson 5 of 9

Related Objects with ForeignKey

A ForeignKey is like a string tied between two toys, so one toy always knows which other toy it belongs to.

What a ForeignKey Represents

A ForeignKey field says 'this row belongs to exactly one row of another model' — like every Tutorial belonging to one Chapter.

Example: What a ForeignKey Represents

Every Tutorial row stores a reference to exactly one Chapter row through its chapter field.

markup
from django.db import models

class Chapter(models.Model):
    title = models.CharField(max_length=200)

class Tutorial(models.Model):
    chapter = models.ForeignKey(Chapter, on_delete=models.CASCADE)
    title = models.CharField(max_length=200)
{# Django-only code -- models.py/views.py/urls.py/settings.py snippets, or template markup using Django template tags/variables -- can't run standalone via Judge0 or the browser preview, since it needs a real Django project. Only this course's pure-Python examples (example_lang == 'python', no Django imports) are actually runnable, so those still get the button below. #}

Accessing the Related Object

Once a ForeignKey is set, you can follow it with simple dot notation to get the full related object, not just its id.

Example: Accessing the Related Object

tutorial.chapter fetches the related Chapter object, and .title reads its title field.

markup
from core.models import Tutorial

tutorial = Tutorial.objects.first()
print(tutorial.chapter.title)
{# Django-only code -- models.py/views.py/urls.py/settings.py snippets, or template markup using Django template tags/variables -- can't run standalone via Judge0 or the browser preview, since it needs a real Django project. Only this course's pure-Python examples (example_lang == 'python', no Django imports) are actually runnable, so those still get the button below. #}

Querying by a Related Field

You can filter on a related model's fields by chaining the relationship name and the field name with double underscores.

Example: Querying by a Related Field

This crosses the ForeignKey to filter tutorials based on a field of their related Chapter, all in one query.

markup
from core.models import Tutorial

# Tutorials whose chapter title contains 'Forms'
Tutorial.objects.filter(chapter__title__icontains='Forms')
{# Django-only code -- models.py/views.py/urls.py/settings.py snippets, or template markup using Django template tags/variables -- can't run standalone via Judge0 or the browser preview, since it needs a real Django project. Only this course's pure-Python examples (example_lang == 'python', no Django imports) are actually runnable, so those still get the button below. #}
Common Mistakes
  1. Forgetting that accessing a ForeignKey's related object (e.g. tutorial.chapter) triggers a new database query each time unless select_related() is used.
  2. Trying to assign a raw id (an integer) to the ForeignKey attribute instead of a model instance or using the _id suffix.
  3. Not handling the case where a ForeignKey is null=True and the related object might be None.
Chapter Summary
  • A ForeignKey field stores a link from one model to another model's row.
  • Accessing the related object is as simple as dot notation, e.g. tutorial.chapter.
  • Django automatically creates a matching _id column in the database for every ForeignKey.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.