one_to_one.txt 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  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 "%s the place" % self.name
  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. .. highlight:: pycon
  31. Create a couple of Places::
  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. >>> r = Restaurant(place=p1, serves_hot_dogs=True, serves_pizza=False)
  38. >>> r.save()
  39. A Restaurant can access its place::
  40. >>> r.place
  41. <Place: Demon Dogs the place>
  42. A Place can access its restaurant, if available::
  43. >>> p1.restaurant
  44. <Restaurant: Demon Dogs the restaurant>
  45. p2 doesn't have an associated restaurant::
  46. >>> from django.core.exceptions import ObjectDoesNotExist
  47. >>> try:
  48. >>> p2.restaurant
  49. >>> except ObjectDoesNotExist:
  50. >>> print("There is no restaurant here.")
  51. There is no restaurant here.
  52. You can also use ``hasattr`` to avoid the need for exception catching::
  53. >>> hasattr(p2, 'restaurant')
  54. False
  55. Set the place using assignment notation. Because place is the primary key on
  56. Restaurant, the save will create a new restaurant::
  57. >>> r.place = p2
  58. >>> r.save()
  59. >>> p2.restaurant
  60. <Restaurant: Ace Hardware the restaurant>
  61. >>> r.place
  62. <Place: Ace Hardware the place>
  63. Set the place back again, using assignment in the reverse direction::
  64. >>> p1.restaurant = r
  65. >>> p1.restaurant
  66. <Restaurant: Demon Dogs the restaurant>
  67. Note that you must save an object before it can be assigned to a one-to-one
  68. relationship. For example, creating a ``Restaurant`` with unsaved ``Place``
  69. raises ``ValueError``::
  70. >>> p3 = Place(name='Demon Dogs', address='944 W. Fullerton')
  71. >>> Restaurant.objects.create(place=p3, serves_hot_dogs=True, serves_pizza=False)
  72. Traceback (most recent call last):
  73. ...
  74. ValueError: save() prohibited to prevent data loss due to unsaved related object 'place'.
  75. Restaurant.objects.all() returns the Restaurants, not the Places. Note that
  76. there are two restaurants - Ace Hardware the Restaurant was created in the call
  77. to r.place = p2::
  78. >>> Restaurant.objects.all()
  79. <QuerySet [<Restaurant: Demon Dogs the restaurant>, <Restaurant: Ace Hardware the restaurant>]>
  80. Place.objects.all() returns all Places, regardless of whether they have
  81. Restaurants::
  82. >>> Place.objects.order_by('name')
  83. <QuerySet [<Place: Ace Hardware the place>, <Place: Demon Dogs the place>]>
  84. You can query the models using :ref:`lookups across relationships <lookups-that-span-relationships>`::
  85. >>> Restaurant.objects.get(place=p1)
  86. <Restaurant: Demon Dogs the restaurant>
  87. >>> Restaurant.objects.get(place__pk=1)
  88. <Restaurant: Demon Dogs the restaurant>
  89. >>> Restaurant.objects.filter(place__name__startswith="Demon")
  90. <QuerySet [<Restaurant: Demon Dogs the restaurant>]>
  91. >>> Restaurant.objects.exclude(place__address__contains="Ashland")
  92. <QuerySet [<Restaurant: Demon Dogs the restaurant>]>
  93. This of course works in reverse::
  94. >>> Place.objects.get(pk=1)
  95. <Place: Demon Dogs the place>
  96. >>> Place.objects.get(restaurant__place=p1)
  97. <Place: Demon Dogs the place>
  98. >>> Place.objects.get(restaurant=r)
  99. <Place: Demon Dogs the place>
  100. >>> Place.objects.get(restaurant__place__name__startswith="Demon")
  101. <Place: Demon Dogs the place>
  102. Add a Waiter to the Restaurant::
  103. >>> w = r.waiter_set.create(name='Joe')
  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>]>