one_to_one.txt 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  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. There is no restaurant here.
  56. You can also use ``hasattr`` to avoid the need for exception catching:
  57. .. code-block:: pycon
  58. >>> hasattr(p2, 'restaurant')
  59. False
  60. Set the place using assignment notation. Because place is the primary key on
  61. Restaurant, the save will create a new restaurant:
  62. .. code-block:: pycon
  63. >>> r.place = p2
  64. >>> r.save()
  65. >>> p2.restaurant
  66. <Restaurant: Ace Hardware the restaurant>
  67. >>> r.place
  68. <Place: Ace Hardware the place>
  69. Set the place back again, using assignment in the reverse direction:
  70. .. code-block:: pycon
  71. >>> p1.restaurant = r
  72. >>> p1.restaurant
  73. <Restaurant: Demon Dogs the restaurant>
  74. Note that you must save an object before it can be assigned to a one-to-one
  75. relationship. For example, creating a ``Restaurant`` with unsaved ``Place``
  76. raises ``ValueError``:
  77. .. code-block:: pycon
  78. >>> p3 = Place(name='Demon Dogs', address='944 W. Fullerton')
  79. >>> Restaurant.objects.create(place=p3, serves_hot_dogs=True, serves_pizza=False)
  80. Traceback (most recent call last):
  81. ...
  82. ValueError: save() prohibited to prevent data loss due to unsaved related object 'place'.
  83. Restaurant.objects.all() returns the Restaurants, not the Places. Note that
  84. there are two restaurants - Ace Hardware the Restaurant was created in the call
  85. to r.place = p2:
  86. .. code-block:: pycon
  87. >>> Restaurant.objects.all()
  88. <QuerySet [<Restaurant: Demon Dogs the restaurant>, <Restaurant: Ace Hardware the restaurant>]>
  89. Place.objects.all() returns all Places, regardless of whether they have
  90. Restaurants:
  91. .. code-block:: pycon
  92. >>> Place.objects.order_by('name')
  93. <QuerySet [<Place: Ace Hardware the place>, <Place: Demon Dogs the place>]>
  94. You can query the models using :ref:`lookups across relationships <lookups-that-span-relationships>`:
  95. .. code-block:: pycon
  96. >>> Restaurant.objects.get(place=p1)
  97. <Restaurant: Demon Dogs the restaurant>
  98. >>> Restaurant.objects.get(place__pk=1)
  99. <Restaurant: Demon Dogs the restaurant>
  100. >>> Restaurant.objects.filter(place__name__startswith="Demon")
  101. <QuerySet [<Restaurant: Demon Dogs the restaurant>]>
  102. >>> Restaurant.objects.exclude(place__address__contains="Ashland")
  103. <QuerySet [<Restaurant: Demon Dogs the restaurant>]>
  104. This also works in reverse:
  105. .. code-block:: pycon
  106. >>> Place.objects.get(pk=1)
  107. <Place: Demon Dogs the place>
  108. >>> Place.objects.get(restaurant__place=p1)
  109. <Place: Demon Dogs the place>
  110. >>> Place.objects.get(restaurant=r)
  111. <Place: Demon Dogs the place>
  112. >>> Place.objects.get(restaurant__place__name__startswith="Demon")
  113. <Place: Demon Dogs the place>
  114. If you delete a place, its restaurant will be deleted (assuming that the
  115. ``OneToOneField`` was defined with
  116. :attr:`~django.db.models.ForeignKey.on_delete` set to ``CASCADE``, which is the
  117. default):
  118. .. code-block:: pycon
  119. >>> p2.delete()
  120. (2, {'one_to_one.Restaurant': 1, 'one_to_one.Place': 1})
  121. >>> Restaurant.objects.all()
  122. <QuerySet [<Restaurant: Demon Dogs the restaurant>]>
  123. Add a Waiter to the Restaurant:
  124. .. code-block:: pycon
  125. >>> w = r.waiter_set.create(name='Joe')
  126. >>> w
  127. <Waiter: Joe the waiter at Demon Dogs the restaurant>
  128. Query the waiters:
  129. .. code-block:: pycon
  130. >>> Waiter.objects.filter(restaurant__place=p1)
  131. <QuerySet [<Waiter: Joe the waiter at Demon Dogs the restaurant>]>
  132. >>> Waiter.objects.filter(restaurant__place__name__startswith="Demon")
  133. <QuerySet [<Waiter: Joe the waiter at Demon Dogs the restaurant>]>