one_to_one.txt 4.9 KB

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