Debian Codegraph @

docs/topics/db/examples/one_to_one.txt

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