Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprenda One-to-One | Relations
Django ORM Ninja: Advanced Techniques for Developers

book
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.

python
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.

python
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.

question mark

How can you access the related Badge object from an Employee instance named employee?

Select the correct answer

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 4. Capítulo 3

Pergunte à IA

expand

Pergunte à IA

ChatGPT

Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo

We use cookies to make your experience better!
some-alt