Related Objects with ForeignKey
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.
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.
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.
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. #}
- Forgetting that accessing a ForeignKey's related object (e.g. tutorial.chapter) triggers a new database query each time unless select_related() is used.
- Trying to assign a raw id (an integer) to the ForeignKey attribute instead of a model instance or using the _id suffix.
- Not handling the case where a ForeignKey is null=True and the related object might be None.
- 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.
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: