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