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
Start learning this pattern below
Jump into concepts and practice - no test required
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.
Practice
OneToOneField?Solution
Step 1: Understand the relationship types in Django
Django provides different fields for relationships: ForeignKey for many-to-one, ManyToManyField for many-to-many, and OneToOneField for one-to-one.Step 2: Identify the purpose of OneToOneField
OneToOneField links exactly one record in one model to exactly one record in another, ensuring a unique pairing.Final Answer:
To link two models so each record in one matches exactly one record in the other -> Option DQuick Check:
OneToOneField = unique pair link [OK]
- Confusing OneToOneField with ForeignKey
- Thinking it allows multiple links per record
- Using it to store multiple values in one field
OneToOneField in a Django model?Solution
Step 1: Check required parameters for OneToOneField
OneToOneField requires the related model and theon_deleteargument to specify behavior on deletion.Step 2: Validate the options
user = models.OneToOneField(User, on_delete=models.CASCADE) correctly includes both the related model andon_delete=models.CASCADE. user = models.OneToOneField(User) misseson_delete, which is mandatory.Final Answer:
user = models.OneToOneField(User, on_delete=models.CASCADE) -> Option CQuick Check:
OneToOneField needs on_delete [OK]
- Omitting on_delete argument
- Using ForeignKey or ManyToManyField instead
- Incorrect field syntax
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
bio = models.TextField()
user = User.objects.create(username='anna')
profile = Profile.objects.create(user=user, bio='Hello!')
print(profile.user.username)What will be printed?
Solution
Step 1: Understand the OneToOneField link
The Profile model links to User via OneToOneField named 'user'. The profile instance has a user with username 'anna'.Step 2: Evaluate the print statement
Accessingprofile.user.usernamefetches the username of the linked User, which is 'anna'.Final Answer:
anna -> Option BQuick Check:
profile.user.username = anna [OK]
- Printing profile.bio instead of username
- Confusing attribute names
- Assuming user attribute is missing
class Employee(models.Model):
user = models.OneToOneField(User)
department = models.CharField(max_length=100)Solution
Step 1: Check OneToOneField requirements
OneToOneField requires theon_deleteargument to specify what happens if the linked User is deleted.Step 2: Analyze the model code
The model misseson_delete, which will cause an error when running migrations or server start.Final Answer:
Missing on_delete argument in OneToOneField -> Option AQuick Check:
OneToOneField needs on_delete [OK]
- Forgetting on_delete causes errors
- Thinking OneToOneField can't link to User
- Confusing field types for department
OneToOneField?Solution
Step 1: Understand extending User without changing it
To add extra info without altering User, create a separate model linked one-to-one to User.Step 2: Choose the correct relationship
OneToOneField in a Profile model allows storing phone number linked uniquely to each User.Final Answer:
Create a new Profile model with a OneToOneField to User and add phone number there -> Option AQuick Check:
Extend User via OneToOneField in separate model [OK]
- Modifying User model directly
- Using ForeignKey or ManyToManyField incorrectly
- Not linking phone number uniquely to User
