A OneToOneField links two database tables so each record in one table matches exactly one record in another. It helps keep related data organized.
OneToOneField for one-to-one in 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.
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)badge.employee.class Employee(models.Model): badge = models.OneToOneField(Badge, on_delete=models.CASCADE, related_name='employee')
primary_key=True makes this field the primary key of Passport.class Passport(models.Model): person = models.OneToOneField(Person, on_delete=models.CASCADE, primary_key=True)
This example shows a Profile model linked one-to-one with Django's User model. Each Profile belongs to exactly one User.
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
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.
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.