Debian Codegraph @

docs/topics/db/examples/many_to_one.txt

raw
1 =========================
2 Many-to-one relationships
3 =========================
4
5 To define a many-to-one relationship, use :class:`~django.db.models.ForeignKey`.
6
7 In this example, a ``Reporter`` can be associated with many ``Article``
8 objects, but an ``Article`` can only have one ``Reporter`` object::
9
10 from django.db import models
11
12
13 class Reporter(models.Model):
14 first_name = models.CharField(max_length=30)
15 last_name = models.CharField(max_length=30)
16 email = models.EmailField()
17
18 def __str__(self):
19 return f"{self.first_name} {self.last_name}"
20
21
22 class Article(models.Model):
23 headline = models.CharField(max_length=100)
24 pub_date = models.DateField()
25 reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)
26
27 def __str__(self):
28 return self.headline
29
30 class Meta:
31 ordering = ["headline"]
32
33 What follows are examples of operations that can be performed using the Python
34 API facilities.
35
36 Create a few Reporters:
37
38 .. code-block:: pycon
39
40 >>> r = Reporter(first_name="John", last_name="Smith", email="[email protected]")
41 >>> r.save()
42
43 >>> r2 = Reporter(first_name="Paul", last_name="Jones", email="[email protected]")
44 >>> r2.save()
45
46 Create an Article:
47
48 .. code-block:: pycon
49
50 >>> from datetime import date
51 >>> a = Article(id=None, headline="This is a test", pub_date=date(2005, 7, 27), reporter=r)
52 >>> a.save()
53
54 >>> a.reporter.id
55 1
56
57 >>> a.reporter
58 <Reporter: John Smith>
59
60 Note that you must save an object before it can be assigned to a foreign key
61 relationship. For example, creating an ``Article`` with unsaved ``Reporter``
62 raises ``ValueError``:
63
64 .. code-block:: pycon
65
66 >>> r3 = Reporter(first_name="John", last_name="Smith", email="[email protected]")
67 >>> Article.objects.create(
68 ... headline="This is a test", pub_date=date(2005, 7, 27), reporter=r3
69 ... )
70 Traceback (most recent call last):
71 ...
72 ValueError: save() prohibited to prevent data loss due to unsaved related object 'reporter'.
73
74 Article objects have access to their related Reporter objects:
75
76 .. code-block:: pycon
77
78 >>> r = a.reporter
79
80 Create an Article via the Reporter object:
81
82 .. code-block:: pycon
83
84 >>> new_article = r.article_set.create(
85 ... headline="John's second story", pub_date=date(2005, 7, 29)
86 ... )
87 >>> new_article
88 <Article: John's second story>
89 >>> new_article.reporter
90 <Reporter: John Smith>
91 >>> new_article.reporter.id
92 1
93
94 Create a new article:
95
96 .. code-block:: pycon
97
98 >>> new_article2 = Article.objects.create(
99 ... headline="Paul's story", pub_date=date(2006, 1, 17), reporter=r
100 ... )
101 >>> new_article2.reporter
102 <Reporter: John Smith>
103 >>> new_article2.reporter.id
104 1
105 >>> r.article_set.all()
106 <QuerySet [<Article: John's second story>, <Article: Paul's story>, <Article: This is a test>]>
107
108 Add the same article to a different article set - check that it moves:
109
110 .. code-block:: pycon
111
112 >>> r2.article_set.add(new_article2)
113 >>> new_article2.reporter.id
114 2
115 >>> new_article2.reporter
116 <Reporter: Paul Jones>
117
118 Adding an object of the wrong type raises TypeError:
119
120 .. code-block:: pycon
121
122 >>> r.article_set.add(r2)
123 Traceback (most recent call last):
124 ...
125 TypeError: 'Article' instance expected, got <Reporter: Paul Jones>
126
127 >>> r.article_set.all()
128 <QuerySet [<Article: John's second story>, <Article: This is a test>]>
129 >>> r2.article_set.all()
130 <QuerySet [<Article: Paul's story>]>
131
132 >>> r.article_set.count()
133 2
134
135 >>> r2.article_set.count()
136 1
137
138 Note that in the last example the article has moved from John to Paul.
139
140 Related managers support field lookups as well.
141 The API automatically follows relationships as far as you need.
142 Use double underscores to separate relationships.
143 This works as many levels deep as you want. There's no limit. For example:
144
145 .. code-block:: pycon
146
147 >>> r.article_set.filter(headline__startswith="This")
148 <QuerySet [<Article: This is a test>]>
149
150 # Find all Articles for any Reporter whose first name is "John".
151 >>> Article.objects.filter(reporter__first_name="John")
152 <QuerySet [<Article: John's second story>, <Article: This is a test>]>
153
154 Exact match is implied here:
155
156 .. code-block:: pycon
157
158 >>> Article.objects.filter(reporter__first_name="John")
159 <QuerySet [<Article: John's second story>, <Article: This is a test>]>
160
161 Query twice over the related field. This translates to an AND condition in the
162 WHERE clause:
163
164 .. code-block:: pycon
165
166 >>> Article.objects.filter(reporter__first_name="John", reporter__last_name="Smith")
167 <QuerySet [<Article: John's second story>, <Article: This is a test>]>
168
169 For the related lookup you can supply a primary key value or pass the related
170 object explicitly:
171
172 .. code-block:: pycon
173
174 >>> Article.objects.filter(reporter__pk=1)
175 <QuerySet [<Article: John's second story>, <Article: This is a test>]>
176 >>> Article.objects.filter(reporter=1)
177 <QuerySet [<Article: John's second story>, <Article: This is a test>]>
178 >>> Article.objects.filter(reporter=r)
179 <QuerySet [<Article: John's second story>, <Article: This is a test>]>
180
181 >>> Article.objects.filter(reporter__in=[1, 2]).distinct()
182 <QuerySet [<Article: John's second story>, <Article: Paul's story>, <Article: This is a test>]>
183 >>> Article.objects.filter(reporter__in=[r, r2]).distinct()
184 <QuerySet [<Article: John's second story>, <Article: Paul's story>, <Article: This is a test>]>
185
186 You can also use a queryset instead of a literal list of instances:
187
188 .. code-block:: pycon
189
190 >>> Article.objects.filter(
191 ... reporter__in=Reporter.objects.filter(first_name="John")
192 ... ).distinct()
193 <QuerySet [<Article: John's second story>, <Article: This is a test>]>
194
195 Querying in the opposite direction:
196
197 .. code-block:: pycon
198
199 >>> Reporter.objects.filter(article__pk=1)
200 <QuerySet [<Reporter: John Smith>]>
201 >>> Reporter.objects.filter(article=1)
202 <QuerySet [<Reporter: John Smith>]>
203 >>> Reporter.objects.filter(article=a)
204 <QuerySet [<Reporter: John Smith>]>
205
206 >>> Reporter.objects.filter(article__headline__startswith="This")
207 <QuerySet [<Reporter: John Smith>, <Reporter: John Smith>, <Reporter: John Smith>]>
208 >>> Reporter.objects.filter(article__headline__startswith="This").distinct()
209 <QuerySet [<Reporter: John Smith>]>
210
211 Counting in the opposite direction works in conjunction with ``distinct()``:
212
213 .. code-block:: pycon
214
215 >>> Reporter.objects.filter(article__headline__startswith="This").count()
216 3
217 >>> Reporter.objects.filter(article__headline__startswith="This").distinct().count()
218 1
219
220 Queries can go round in circles:
221
222 .. code-block:: pycon
223
224 >>> Reporter.objects.filter(article__reporter__first_name__startswith="John")
225 <QuerySet [<Reporter: John Smith>, <Reporter: John Smith>, <Reporter: John Smith>, <Reporter: John Smith>]>
226 >>> Reporter.objects.filter(article__reporter__first_name__startswith="John").distinct()
227 <QuerySet [<Reporter: John Smith>]>
228 >>> Reporter.objects.filter(article__reporter=r).distinct()
229 <QuerySet [<Reporter: John Smith>]>
230
231 If you delete a reporter, their articles will be deleted (assuming that the
232 ForeignKey was defined with :attr:`django.db.models.ForeignKey.on_delete` set to
233 ``CASCADE``, which is the default):
234
235 .. code-block:: pycon
236
237 >>> Article.objects.all()
238 <QuerySet [<Article: John's second story>, <Article: Paul's story>, <Article: This is a test>]>
239 >>> Reporter.objects.order_by("first_name")
240 <QuerySet [<Reporter: John Smith>, <Reporter: Paul Jones>]>
241 >>> r2.delete()
242 >>> Article.objects.all()
243 <QuerySet [<Article: John's second story>, <Article: This is a test>]>
244 >>> Reporter.objects.order_by("first_name")
245 <QuerySet [<Reporter: John Smith>]>
246
247 You can delete using a JOIN in the query:
248
249 .. code-block:: pycon
250
251 >>> Reporter.objects.filter(article__headline__startswith="This").delete()
252 >>> Reporter.objects.all()
253 <QuerySet []>
254 >>> Article.objects.all()
255 <QuerySet []>