0
0
Djangoframework~5 mins

OneToOneField for one-to-one in Django

Choose your learning style9 modes available
Introduction

A OneToOneField links two database tables so each record in one table matches exactly one record in another. It helps keep related data organized.

You want to store extra information about a user in a separate table.
You have two models where each item in one must have exactly one matching item in the other.
You want to split a big model into smaller parts but keep a strict one-to-one link.
You need to extend a built-in Django model like User with custom fields.
You want to ensure no duplicates or multiple links between two models.
Syntax
Django
class ModelName(models.Model):
    field_name = models.OneToOneField(
        OtherModel,
        on_delete=models.CASCADE,
        related_name='related_name_optional',
        primary_key=False
    )

on_delete=models.CASCADE means if the linked record is deleted, this one deletes too.

related_name lets you access the reverse link from the other model.

Examples
Each Profile links to exactly one User. If the User is deleted, the Profile is deleted too.
Django
class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
You can access the Employee from a Badge using badge.employee.
Django
class Employee(models.Model):
    badge = models.OneToOneField(Badge, on_delete=models.CASCADE, related_name='employee')
Using primary_key=True makes this field the primary key of Passport.
Django
class Passport(models.Model):
    person = models.OneToOneField(Person, on_delete=models.CASCADE, primary_key=True)
Sample Program

This example shows a Profile model linked one-to-one with Django's User model. Each Profile belongs to exactly one User.

Django
from django.db import models
from django.contrib.auth.models import User

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

# Usage example (in Django shell):
# user = User.objects.create(username='alice')
# profile = Profile.objects.create(user=user, bio='Hello!')
# print(profile.user.username)
# Output: alice
OutputSuccess
Important Notes

Always set on_delete to control what happens when the linked record is deleted.

OneToOneField creates a unique constraint automatically, so no two records can link to the same target.

You can access the linked object from either side using the field name or related_name.

Summary

OneToOneField links two models so each record matches exactly one record in the other.

Use it to extend models or keep related data in separate tables.

Remember to set on_delete and optionally related_name for easy access.