one_to_one.txt 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. ========================
  2. One-to-one relationships
  3. ========================
  4. To define a one-to-one relationship, use
  5. :class:`~django.db.models.OneToOneField`.
  6. In this example, a ``Place`` optionally can be a ``Restaurant``::
  7. from django.db import models
  8. class Place(models.Model):
  9. name = models.CharField(max_length=50)
  10. address = models.CharField(max_length=80)
  11. def __str__(self):
  12. return f"{self.name} the place"
  13. class Restaurant(models.Model):
  14. place = models.OneToOneField(
  15. Place,
  16. on_delete=models.CASCADE,
  17. primary_key=True,
  18. )
  19. serves_hot_dogs = models.BooleanField(default=False)
  20. serves_pizza = models.BooleanField(default=False)
  21. def __str__(self):
  22. return "%s the restaurant" % self.place.name
  23. class Waiter(models.Model):
  24. restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE)
  25. name = models.CharField(max_length=50)
  26. def __str__(self):
  27. return "%s the waiter at %s" % (self.name, self.restaurant)
  28. What follows are examples of operations that can be performed using the Python
  29. API facilities.
  30. Create a couple of Places:
  31. .. code-block:: pycon
  32. >>> p1 = Place(name="Demon Dogs", address="944 W. Fullerton")
  33. >>> p1.save()
  34. >>> p2 = Place(name="Ace Hardware", address="1013 N. Ashland")
  35. >>> p2.save()
  36. Create a Restaurant. Pass the "parent" object as this object's primary key:
  37. .. code-block:: pycon
  38. >>> r = Restaurant(place=p1, serves_hot_dogs=True, serves_pizza=False)
  39. >>> r.save()
  40. A Restaurant can access its place:
  41. .. code-block:: pycon
  42. >>> r.place
  43. <Place: Demon Dogs the place>
  44. A Place can access its restaurant, if available:
  45. .. code-block:: pycon
  46. >>> p1.restaurant
  47. <Restaurant: Demon Dogs the restaurant>
  48. p2 doesn't have an associated restaurant:
  49. .. code-block:: pycon
  50. >>> from django.core.exceptions import ObjectDoesNotExist
  51. >>> try:
  52. ... p2.restaurant
  53. ... except ObjectDoesNotExist:
  54. ... print("There is no restaurant here.")
  55. ...
  56. There is no restaurant here.
  57. You can also use ``hasattr`` to avoid the need for exception catching:
  58. .. code-block:: pycon
  59. >>> hasattr(p2, "restaurant")
  60. False
  61. Set the place using assignment notation. Because place is the primary key on
  62. Restaurant, the save will create a new restaurant:
  63. .. code-block:: pycon
  64. >>> r.place = p2
  65. >>> r.save()
  66. >>> p2.restaurant
  67. <Restaurant: Ace Hardware the restaurant>
  68. >>> r.place
  69. <Place: Ace Hardware the place>
  70. Set the place back again, using assignment in the reverse direction:
  71. .. code-block:: pycon
  72. >>> p1.restaurant = r
  73. >>> p1.restaurant
  74. <Restaurant: Demon Dogs the restaurant>
  75. Note that you must save an object before it can be assigned to a one-to-one
  76. relationship. For example, creating a ``Restaurant`` with unsaved ``Place``
  77. raises ``ValueError``:
  78. .. code-block:: pycon
  79. >>> p3 = Place(name="Demon Dogs", address="944 W. Fullerton")
  80. >>> Restaurant.objects.create(place=p3, serves_hot_dogs=True, serves_pizza=False)
  81. Traceback (most recent call last):
  82. ...
  83. ValueError: save() prohibited to prevent data loss due to unsaved related object 'place'.
  84. Restaurant.objects.all() returns the Restaurants, not the Places. Note that
  85. there are two restaurants - Ace Hardware the Restaurant was created in the call
  86. to r.place = p2:
  87. .. code-block:: pycon
  88. >>> Restaurant.objects.all()
  89. <QuerySet [<Restaurant: Demon Dogs the restaurant>, <Restaurant: Ace Hardware the restaurant>]>
  90. Place.objects.all() returns all Places, regardless of whether they have
  91. Restaurants:
  92. .. code-block:: pycon
  93. >>> Place.objects.order_by("name")
  94. <QuerySet [<Place: Ace Hardware the place>, <Place: Demon Dogs the place>]>
  95. You can query the models using :ref:`lookups across relationships <lookups-that-span-relationships>`:
  96. .. code-block:: pycon
  97. >>> Restaurant.objects.get(place=p1)
  98. <Restaurant: Demon Dogs the restaurant>
  99. >>> Restaurant.objects.get(place__pk=1)
  100. <Restaurant: Demon Dogs the restaurant>
  101. >>> Restaurant.objects.filter(place__name__startswith="Demon")
  102. <QuerySet [<Restaurant: Demon Dogs the restaurant>]>
  103. >>> Restaurant.objects.exclude(place__address__contains="Ashland")
  104. <QuerySet [<Restaurant: Demon Dogs the restaurant>]>
  105. This also works in reverse:
  106. .. code-block:: pycon
  107. >>> Place.objects.get(pk=1)
  108. <Place: Demon Dogs the place>
  109. >>> Place.objects.get(restaurant__place=p1)
  110. <Place: Demon Dogs the place>
  111. >>> Place.objects.get(restaurant=r)
  112. <Place: Demon Dogs the place>
  113. >>> Place.objects.get(restaurant__place__name__startswith="Demon")
  114. <Place: Demon Dogs the place>
  115. If you delete a place, its restaurant will be deleted (assuming that the
  116. ``OneToOneField`` was defined with
  117. :attr:`~django.db.models.ForeignKey.on_delete` set to ``CASCADE``, which is the
  118. default):
  119. .. code-block:: pycon
  120. >>> p2.delete()
  121. (2, {'one_to_one.Restaurant': 1, 'one_to_one.Place': 1})
  122. >>> Restaurant.objects.all()
  123. <QuerySet [<Restaurant: Demon Dogs the restaurant>]>
  124. Add a Waiter to the Restaurant:
  125. .. code-block:: pycon
  126. >>> w = r.waiter_set.create(name="Joe")
  127. >>> w
  128. <Waiter: Joe the waiter at Demon Dogs the restaurant>
  129. Query the waiters:
  130. .. code-block:: pycon
  131. >>> Waiter.objects.filter(restaurant__place=p1)
  132. <QuerySet [<Waiter: Joe the waiter at Demon Dogs the restaurant>]>
  133. >>> Waiter.objects.filter(restaurant__place__name__startswith="Demon")
  134. <QuerySet [<Waiter: Joe the waiter at Demon Dogs the restaurant>]>