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

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

question mark

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

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 4.  3

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 4.  3
some-alt