Model Relationships
Real data is connected. An event belongs to a category, is run by an organiser and is attended by many students. Django models express these links with three relationship fields: ForeignKey, ManyToManyField and OneToOneField.
The three kinds of relationship
| Relationship | Field | Campus Events example |
|---|---|---|
| Many-to-one (one-to-many) | ForeignKey | Many events belong to one category; one user organises many events |
| Many-to-many | ManyToManyField | An event has many attendees, and a student attends many events |
| One-to-one | OneToOneField | Each user has exactly one profile |
Adding relationships to the Event model
We'll add a Category model and three relationship fields to Event. Users come from Django's built-in auth app; refer to the user model with settings.AUTH_USER_MODEL rather than importing User directly, so your code keeps working if the project later switches to a custom user model.
events/models.py
from django.conf import settings
from django.db import models
from django.urls import reverse
class Category(models.Model):
name = models.CharField(max_length=50, unique=True)
class Meta:
ordering = ["name"]
verbose_name_plural = "categories"
def __str__(self):
return self.name
class Event(models.Model):
title = models.CharField(max_length=200)
description = models.TextField(blank=True)
venue = models.CharField(max_length=100)
starts_at = models.DateTimeField()
capacity = models.PositiveIntegerField(default=50)
is_free = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add=True)
category = models.ForeignKey(
Category,
on_delete=models.SET_NULL,
null=True,
blank=True,
related_name="events",
)
organiser = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
null=True,
blank=True,
related_name="organised_events",
)
attendees = models.ManyToManyField(
settings.AUTH_USER_MODEL,
blank=True,
related_name="events_attending",
)
class Meta:
ordering = ["starts_at"]
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("events:event_detail", args=[self.pk])
We made category and organiser nullable because events already exist in the database without them. Create and apply the migration:
python manage.py makemigrations events --name categories_and_people python manage.py migrate
In the database, a ForeignKey becomes a column such as category_id holding the related row's ID. A ManyToManyField creates a separate join table (here events_event_attendees) with one row per event–attendee pair. Django manages both for you.
What happens on delete?
on_delete is required on every ForeignKey and OneToOneField. It decides what happens to an event when the object it points to is deleted:
| Option | Effect | Good for |
|---|---|---|
CASCADE | Delete the events too | Data that makes no sense alone, e.g. comments on a deleted post |
PROTECT | Refuse to delete while events still point to it | Important records, e.g. a SACCO member with loans |
SET_NULL | Set the field to NULL (needs null=True) | Optional links, e.g. removing a category |
SET_DEFAULT | Set the field to its default | Moving items to a fallback value |
DO_NOTHING | Do nothing in Django; the database decides | Rarely; advanced cases only |
Working with related objects
Continuing in python manage.py shell with the events from the ORM Queries page and the superuser amina from The Admin Site:
>>> from django.contrib.auth.models import User >>> from events.models import Category, Event >>> tech = Category.objects.create(name="Tech") >>> hack = Event.objects.get(title="Campus Hackathon") >>> hack.category = tech >>> hack.save() >>> hack.category.name 'Tech' >>> tech.events.all() <QuerySet [<Event: Campus Hackathon>]> >>> Event.objects.filter(category__name="Tech") <QuerySet [<Event: Campus Hackathon>]>
- Forward access:
hack.categoryfollows the foreign key to theCategoryobject. - Reverse access:
tech.eventsgoes the other way, using therelated_namewe chose. Withoutrelated_nameit would betech.event_set. - Lookups across relationships:
category__namefollows the link inside a query, which Django turns into a SQL JOIN.
Many-to-many fields have methods for adding and removing links:
>>> amina = User.objects.get(username="amina") >>> hack.attendees.add(amina) >>> hack.attendees.count() 1 >>> amina.events_attending.all() <QuerySet [<Event: Campus Hackathon>]> >>> hack.attendees.remove(amina) >>> hack.attendees.count() 0
There are also set([...]) to replace all links at once and clear() to remove them all. Changes made with add() and remove() are saved immediately; you don't call save().
Pointing two fields at the same model without different related_name values. Here both organiser and attendees link to the user model; without unique names, both would want to be called user.event_set and Django stops with a "reverse accessor clashes" error (fields.E304).
One-to-one: a student profile
Use OneToOneField to extend another model with extra information, e.g. a profile for each user:
accounts/models.py
from django.conf import settings
from django.db import models
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
course = models.CharField(max_length=100, blank=True)
phone = models.CharField(max_length=15, blank=True)
def __str__(self):
return f"Profile of {self.user.username}"
Access it from either side: profile.user and user.profile. If a user has no profile yet, user.profile raises RelatedObjectDoesNotExist.
Relationships in templates and efficient queries
events/templates/events/event_detail.html
<p>Category: {{ event.category.name|default:"Uncategorised" }}</p>
<p>Organised by {{ event.organiser.username|default:"the events team" }}</p>
<p>{{ event.attendees.count }} of {{ event.capacity }} places taken</p>
<ul>
{% for person in event.attendees.all %}
<li>{{ person.username }}</li>
{% endfor %}
</ul>
On a list page, writing {{ event.category.name }} inside a loop runs one extra query per event: the "N+1 queries" problem. Load related data up front instead:
events = (
Event.objects
.select_related("category", "organiser") # ForeignKey / OneToOne: one JOINed query
.prefetch_related("attendees") # ManyToMany: one extra query in total
)
In the admin, filter_horizontal = ["attendees"] on EventAdmin gives a much friendlier widget for picking many users, and adding "category" to list_filter lets staff filter by category.
Key points
ForeignKeyis many-to-one,ManyToManyFieldis many-to-many andOneToOneFieldis one-to-one.- Every
ForeignKeyneedson_delete; chooseCASCADE,PROTECTorSET_NULLdeliberately. - Use
related_namefor clear reverse access, andsettings.AUTH_USER_MODELto link to users. - Use
add(),remove(),set()andclear()on many-to-many fields. - Use
select_related()andprefetch_related()to avoid N+1 queries.
Tip: use the ← and → keys to move between pages.
