Gareth D.
—Should you use a OneToOneField
or a ForeignKey
for your Django model?
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
.
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.
┌──────┐ ┌──────┐ │ Book │◀──┬──┤Author│ ├──────┤ │ ├──────┤ │ │ │ │ │ │ │ │ │ │ └──────┘ │ └──────┘ ┌──────┐ │ │ Book │◀──┘ ├──────┤ │ │ │ │ └──────┘
In Django, this might look as follows:
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)
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).
┌────────┐ ┌──────┐ │UserInfo│◀─────┤ User │ ├──── ────┤ ├──────┤ │ │ │ │ │ │ │ │ └────────┘ └──────┘
In Django, this might look as follows:
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
:
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:
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.
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'`
Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.
SEE EPISODESConsidered “not bad” by 4 million developers and more than 100,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.
Here’s a quick look at how Sentry handles your personal information (PII).
×We collect PII about people browsing our website, users of the Sentry service, prospective customers, and people who otherwise interact with us.
What if my PII is included in data sent to Sentry by a Sentry customer (e.g., someone using Sentry to monitor their app)? In this case you have to contact the Sentry customer (e.g., the maker of the app). We do not control the data that is sent to us through the Sentry service for the purposes of application monitoring.
Am I included?We may disclose your PII to the following type of recipients:
You may have the following rights related to your PII:
If you have any questions or concerns about your privacy at Sentry, please email us at [email protected].
If you are a California resident, see our Supplemental notice.