One-to-One
A One-to-One relationship is used when one object of a model corresponds to exactly one object of another model. For example, a table of employees and another table of employee ID badges, where each employee has exactly one unique ID badge. To specify a One-to-One relation, use models.OneToOneField
.
id_badge = models.OneToOneField(IdBadge, on_delete=models.CASCADE, related_name=employee)
OneToOneField accepts all of the extra arguments accepted by ForeignKey.
There is just an example of usage One-to-One relations. We will not use it in our project.
from django.db import models
class Employee(models.Model):
name = models.CharField(max_length=100)
position = models.CharField(max_length=100)
class Badge(models.Model):
employee = models.OneToOneField(Employee, on_delete=models.CASCADE, related_name="badge")
badge_number = models.CharField(max_length=50)
issue_date = models.DateField()
employee = Employee.objects.get(name="Jane Doe")
employee_badge = employee.badge # Accessing Badge through Employee instance
badge = Badge.objects.get(badge_number="123456789")
employee = badge.employee # Accessing Employee from Badge instance
You can learn more about this relation in the official documentation.
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat
Awesome!
Completion rate improved to 3.57
One-to-One
Swipe to show menu
A One-to-One relationship is used when one object of a model corresponds to exactly one object of another model. For example, a table of employees and another table of employee ID badges, where each employee has exactly one unique ID badge. To specify a One-to-One relation, use models.OneToOneField
.
id_badge = models.OneToOneField(IdBadge, on_delete=models.CASCADE, related_name=employee)
OneToOneField accepts all of the extra arguments accepted by ForeignKey.
There is just an example of usage One-to-One relations. We will not use it in our project.
from django.db import models
class Employee(models.Model):
name = models.CharField(max_length=100)
position = models.CharField(max_length=100)
class Badge(models.Model):
employee = models.OneToOneField(Employee, on_delete=models.CASCADE, related_name="badge")
badge_number = models.CharField(max_length=50)
issue_date = models.DateField()
employee = Employee.objects.get(name="Jane Doe")
employee_badge = employee.badge # Accessing Badge through Employee instance
badge = Badge.objects.get(badge_number="123456789")
employee = badge.employee # Accessing Employee from Badge instance
You can learn more about this relation in the official documentation.
Thanks for your feedback!