Skip to content
Kuza Ndoto Academy

Model Relationships

IntermediateChapter 4 · Page 16 of 235 min readUpdated 15 Nov 2026

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

RelationshipFieldCampus Events example
Many-to-one (one-to-many)ForeignKeyMany events belong to one category; one user organises many events
Many-to-manyManyToManyFieldAn event has many attendees, and a student attends many events
One-to-oneOneToOneFieldEach 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
Migrations for 'events': events/migrations/0003_categories_and_people.py + Create model Category + Add field attendees to event + Add field category to event + Add field organiser to event Operations to perform: Apply all migrations: admin, auth, contenttypes, events, sessions Running migrations: Applying events.0003_categories_and_people... OK

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.

Category name Event category_id organiser_id User username category ForeignKey 1 * organiser ForeignKey * 1 events_event_attendees event_id, user_id attendees (ManyToMany)
Figure 1. A ForeignKey is a single column on Event pointing to one row; the many-to-many link lives in its own join table with one row per event–attendee pair.

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:

OptionEffectGood for
CASCADEDelete the events tooData that makes no sense alone, e.g. comments on a deleted post
PROTECTRefuse to delete while events still point to itImportant records, e.g. a SACCO member with loans
SET_NULLSet the field to NULL (needs null=True)Optional links, e.g. removing a category
SET_DEFAULTSet the field to its defaultMoving items to a fallback value
DO_NOTHINGDo nothing in Django; the database decidesRarely; advanced cases only

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.category follows the foreign key to the Category object.
  • Reverse access: tech.events goes the other way, using the related_name we chose. Without related_name it would be tech.event_set.
  • Lookups across relationships: category__name follows 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().

Common mistake

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

  • ForeignKey is many-to-one, ManyToManyField is many-to-many and OneToOneField is one-to-one.
  • Every ForeignKey needs on_delete; choose CASCADE, PROTECT or SET_NULL deliberately.
  • Use related_name for clear reverse access, and settings.AUTH_USER_MODEL to link to users.
  • Use add(), remove(), set() and clear() on many-to-many fields.
  • Use select_related() and prefetch_related() to avoid N+1 queries.
Up next · New chapter: Forms & UsersDjango FormsCollect and validate user input.
→

Tip: use the ← and → keys to move between pages.