In Django, a one-to-one relationship can be added to a model using the OneToOneField
. This type of relationship implies that each instance of a model is related to one and only one instance of another model. Here is an example to illustrate how you can define a one-to-one relationship between two models, Person
and Passport
.
Example
Let’s say you have two models: Person
and Passport
. Each person has one passport, and each passport is associated with one person.
- Define the Models
from django.db import models class Person(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) birthdate = models.DateField() def __str__(self): return f"{self.first_name} {self.last_name}" class Passport(models.Model): passport_number = models.CharField(max_length=20, unique=True) issue_date = models.DateField() expiry_date = models.DateField() person = models.OneToOneField(Person, on_delete=models.CASCADE) def __str__(self): return self.passport_number
- Migrations
After defining your models, you need to create and apply the migrations to reflect these changes in your database.
python manage.py makemigrations python manage.py migrate
- Usage
You can now create instances of these models and establish the one-to-one relationship.
from myapp.models import Person, Passport # Create a Person instance person = Person.objects.create(first_name="John", last_name="Doe", birthdate="1990-01-01") # Create a Passport instance linked to the Person instance passport = Passport.objects.create(passport_number="A12345678", issue_date="2022-01-01", expiry_date="2032-01-01", person=person) # Access the related objects print(passport.person.first_name) # Output: John print(person.passport.passport_number) # Output: A12345678
Key Points
OneToOneField
: This is used to create a one-to-one relationship. It should be defined in the model that will have the foreign key.on_delete=models.CASCADE
: This parameter specifies that when the referencedPerson
object is deleted, the associatedPassport
object should also be deleted.- Backward Relationship: Django automatically creates a backward relationship, allowing you to access the related
Passport
instance from aPerson
instance usingperson.passport
.
This setup ensures that each Person
has exactly one Passport
and vice versa.