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.
Takk for tilbakemeldingene dine!
Spør AI
Spør AI
Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår
Awesome!
Completion rate improved to 3.57
One-to-One
Sveip for å vise menyen
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.
Takk for tilbakemeldingene dine!