0
0
DjangoConceptBeginner · 3 min read

What is OneToOneField in Django: Explanation and Example

In Django, OneToOneField creates a one-to-one relationship between two models, meaning each record in one model links to exactly one record in another. It is like a unique connection, ensuring no duplicates on either side.
⚙️

How It Works

Imagine you have two sets of data, like people and their passports. Each person has exactly one passport, and each passport belongs to exactly one person. OneToOneField in Django models this kind of relationship.

Under the hood, it creates a unique link between two tables in the database. This means if you have a model for users and another for profiles, each profile is connected to one user only, and no two profiles can share the same user.

This is different from ForeignKey, which allows many records to link to one record, and from ManyToManyField, which allows many records on both sides.

💻

Example

This example shows two models: User and Profile. Each Profile is linked to exactly one User using OneToOneField.

python
from django.db import models

class User(models.Model):
    username = models.CharField(max_length=100)

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField()

# Usage example (in Django shell):
# user = User.objects.create(username='alice')
# profile = Profile.objects.create(user=user, bio='Hello, I am Alice!')
# print(profile.user.username)  # Output: alice
Output
alice
🎯

When to Use

Use OneToOneField when you want to extend a model with extra information without changing the original model. For example, adding a profile to a user, where each user has only one profile.

It is also useful when splitting data into separate tables for organization or security, like separating sensitive info from general user data.

Real-world cases include linking a user to a profile, a car to its registration, or an employee to their company badge.

Key Points

  • One-to-one link: Each record connects to exactly one record in another model.
  • Unique constraint: Ensures no duplicates on either side of the relationship.
  • Use for extension: Ideal for adding extra info without changing the original model.
  • On delete cascade: Deleting the linked record removes the related one automatically.

Key Takeaways

OneToOneField creates a unique, one-to-one link between two Django models.
It is perfect for extending models with additional related data.
Each side of the relationship can have only one matching record.
Deleting the linked record can cascade and delete the related record.
Use it when you want a strict one-to-one connection, unlike ForeignKey or ManyToManyField.