What's the difference between Django's OneToOneField and ForeignKey?

Gareth D.

The Problem

Should you use a OneToOneField or a ForeignKey for your Django model?

The Solution

A ForeignKey relates objects in a relational database with a many-to-one relationship, while a OneToOneField, as the name implies, creates a one-to-one relationship. In most cases, if you’re defining two models that are related to each other, you’ll want to use a ForeignKey.

ForeignKey example

If you assume a simplified world where every book is written by exactly one author, but a single author can write many books, then you don’t want to keep all information about both the book and the author in the same model, because you will end up with a lot of duplication. Instead, it is better to store the Author details in a separate table and then only store a reference to that author in your Book model: it uses less space, and if you need to update any information about the author, you only need to make the change in one place.

Click to Copy
┌──────┐ ┌──────┐ │ Book │◀──┬──┤Author│ ├──────┤ │ ├──────┤ │ │ │ │ │ │ │ │ │ │ └──────┘ │ └──────┘ ┌──────┐ │ │ Book │◀──┘ ├──────┤ │ │ │ │ └──────┘

In Django, this might look as follows:

Click to Copy
from django.db import models class Author(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) class Book(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) title = models.CharField(max_length=100) isbn = models.CharField(max_length=100)

One-to-One example

By contrast, a OneToOneField means that there is only a single object on both sides of the relationship. For example, you might store basic information (such as a username and email address) about your users in a User object, and then have a separate UserInfo object for additional information (such as a phone number, social links, biography, etc.).

In this case, each User has at most one UserInfo object, and no two users share the same UserInfo object, so you can use a one-to-one mapping to enforce this.

Whenever you have a one-to-one mapping, it’s usually better to simply add more fields to the first object. In this case, you could add (maybe optional) attributes directly to the User object to account for the extra fields. But sometimes it might be necessary to have a separate object — for example, if you store the User object differently (maybe with encryption, or on a separate authentication server).

Click to Copy
┌────────┐ ┌──────┐ │UserInfo│◀─────┤ User │ ├────────┤ ├──────┤ │ │ │ │ │ │ │ │ └────────┘ └──────┘

In Django, this might look as follows:

Click to Copy
class User(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) class UserInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone_number = models.CharField(max_length=100)

If you prefer to use a ForeignKey, but still want to enforce a one-to-one mapping, you can use unique=True for a very similar result to using a OneToOneField:

Click to Copy
class User(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) class UserInfo(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, unique=True) phone_number = models.CharField(max_length=100)

Note that when retrieving models, things will work a bit differently if you use an explicit OneToOneField instead of an implicit one using ForeignKey and unique=True. When using a ForiegnKey, even with the unique=True constraint, you can still get a Django QuerySet of related objects:

Click to Copy
u = User.objects.first() u.userinfo_set.all() # <QuerySet [<UserInfo: UserInfo object (5)>]>

The QuerySet will always contain at most one item, but because the constraint is enforced only at save time, it is still modeled internally as a set. When using a OneToOneField, Django knows that looking for a collection of related objects (when there can only be one) doesn’t make sense and will throw an error.

Click to Copy
u = User.objects.first() u.userinfo_set.all() # Traceback (most recent call last): # File "<console>", line 1, in <module> # AttributeError: 'User' object has no attribute 'userinfo_set'`

Loved by over 4 million developers and more than 90,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.

Share on Twitter
Bookmark this page
Ask a questionJoin the discussion

Related Answers

A better experience for your users. An easier life for your developers.

    TwitterGitHubDribbbleLinkedinDiscord
© 2024 • Sentry is a registered Trademark
of Functional Software, Inc.