Debian Codegraph @

docs/topics/db/examples/many_to_many.txt

raw
1 ==========================
2 Many-to-many relationships
3 ==========================
4
5 To define a many-to-many relationship, use
6 :class:`~django.db.models.ManyToManyField`.
7
8 In this example, an ``Article`` can be published in multiple ``Publication``
9 objects, and a ``Publication`` has multiple ``Article`` objects:
10
11 .. code-block:: python
12
13 from django.db import models
14
15
16 class Publication(models.Model):
17 title = models.CharField(max_length=30)
18
19 class Meta:
20 ordering = ["title"]
21
22 def __str__(self):
23 return self.title
24
25
26 class Article(models.Model):
27 headline = models.CharField(max_length=100)
28 publications = models.ManyToManyField(Publication)
29
30 class Meta:
31 ordering = ["headline"]
32
33 def __str__(self):
34 return self.headline
35
36 What follows are examples of operations that can be performed using the Python
37 API facilities.
38
39 Create a few ``Publication`` instances:
40
41 .. code-block:: pycon
42
43 >>> p1 = Publication(title="The Python Journal")
44 >>> p1.save()
45 >>> p2 = Publication(title="Science News")
46 >>> p2.save()
47 >>> p3 = Publication(title="Science Weekly")
48 >>> p3.save()
49
50 Create an ``Article``:
51
52 .. code-block:: pycon
53
54 >>> a1 = Article(headline="Django lets you build web apps easily")
55
56 You can't associate it with a ``Publication`` until it's been saved:
57
58 .. code-block:: pycon
59
60 >>> a1.publications.add(p1)
61 Traceback (most recent call last):
62 ...
63 ValueError: "<Article: Django lets you build web apps easily>" needs to have a value for field "id" before this many-to-many relationship can be used.
64
65 Save it!
66
67 .. code-block:: pycon
68
69 >>> a1.save()
70
71 Associate the ``Article`` with a ``Publication``:
72
73 .. code-block:: pycon
74
75 >>> a1.publications.add(p1)
76
77 Create another ``Article``, and set it to appear in its publications:
78
79 .. code-block:: pycon
80
81 >>> a2 = Article(headline="NASA uses Python")
82 >>> a2.save()
83 >>> a2.publications.add(p1, p2)
84 >>> a2.publications.add(p3)
85
86 Adding a second time is OK, it will not duplicate the relation:
87
88 .. code-block:: pycon
89
90 >>> a2.publications.add(p3)
91
92 Adding an object of the wrong type raises :exc:`TypeError`:
93
94 .. code-block:: pycon
95
96 >>> a2.publications.add(a1)
97 Traceback (most recent call last):
98 ...
99 TypeError: 'Publication' instance expected
100
101 Create and add a ``Publication`` to an ``Article`` in one step using
102 :meth:`~django.db.models.fields.related.RelatedManager.create`:
103
104 .. code-block:: pycon
105
106 >>> new_publication = a2.publications.create(title="Highlights for Children")
107
108 ``Article`` objects have access to their related ``Publication`` objects:
109
110 .. code-block:: pycon
111
112 >>> a1.publications.all()
113 <QuerySet [<Publication: The Python Journal>]>
114 >>> a2.publications.all()
115 <QuerySet [<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>, <Publication: The Python Journal>]>
116
117 ``Publication`` objects have access to their related ``Article`` objects:
118
119 .. code-block:: pycon
120
121 >>> p2.article_set.all()
122 <QuerySet [<Article: NASA uses Python>]>
123 >>> p1.article_set.all()
124 <QuerySet [<Article: Django lets you build web apps easily>, <Article: NASA uses Python>]>
125 >>> Publication.objects.get(id=4).article_set.all()
126 <QuerySet [<Article: NASA uses Python>]>
127
128 Many-to-many relationships can be queried using :ref:`lookups across
129 relationships <lookups-that-span-relationships>`:
130
131 .. code-block:: pycon
132
133 >>> Article.objects.filter(publications__id=1)
134 <QuerySet [<Article: Django lets you build web apps easily>, <Article: NASA uses Python>]>
135 >>> Article.objects.filter(publications__pk=1)
136 <QuerySet [<Article: Django lets you build web apps easily>, <Article: NASA uses Python>]>
137 >>> Article.objects.filter(publications=1)
138 <QuerySet [<Article: Django lets you build web apps easily>, <Article: NASA uses Python>]>
139 >>> Article.objects.filter(publications=p1)
140 <QuerySet [<Article: Django lets you build web apps easily>, <Article: NASA uses Python>]>
141
142 >>> Article.objects.filter(publications__title__startswith="Science")
143 <QuerySet [<Article: NASA uses Python>, <Article: NASA uses Python>]>
144
145 >>> Article.objects.filter(publications__title__startswith="Science").distinct()
146 <QuerySet [<Article: NASA uses Python>]>
147
148 The :meth:`~django.db.models.query.QuerySet.count` function respects
149 :meth:`~django.db.models.query.QuerySet.distinct` as well:
150
151 .. code-block:: pycon
152
153 >>> Article.objects.filter(publications__title__startswith="Science").count()
154 2
155
156 >>> Article.objects.filter(publications__title__startswith="Science").distinct().count()
157 1
158
159 >>> Article.objects.filter(publications__in=[1, 2]).distinct()
160 <QuerySet [<Article: Django lets you build web apps easily>, <Article: NASA uses Python>]>
161 >>> Article.objects.filter(publications__in=[p1, p2]).distinct()
162 <QuerySet [<Article: Django lets you build web apps easily>, <Article: NASA uses Python>]>
163
164 Reverse m2m queries are supported (i.e., starting at the table that doesn't have
165 a :class:`~django.db.models.ManyToManyField`):
166
167 .. code-block:: pycon
168
169 >>> Publication.objects.filter(id=1)
170 <QuerySet [<Publication: The Python Journal>]>
171 >>> Publication.objects.filter(pk=1)
172 <QuerySet [<Publication: The Python Journal>]>
173
174 >>> Publication.objects.filter(article__headline__startswith="NASA")
175 <QuerySet [<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>, <Publication: The Python Journal>]>
176
177 >>> Publication.objects.filter(article__id=1)
178 <QuerySet [<Publication: The Python Journal>]>
179 >>> Publication.objects.filter(article__pk=1)
180 <QuerySet [<Publication: The Python Journal>]>
181 >>> Publication.objects.filter(article=1)
182 <QuerySet [<Publication: The Python Journal>]>
183 >>> Publication.objects.filter(article=a1)
184 <QuerySet [<Publication: The Python Journal>]>
185
186 >>> Publication.objects.filter(article__in=[1, 2]).distinct()
187 <QuerySet [<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>, <Publication: The Python Journal>]>
188 >>> Publication.objects.filter(article__in=[a1, a2]).distinct()
189 <QuerySet [<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>, <Publication: The Python Journal>]>
190
191 Excluding a related item works as you would expect, too (although the SQL
192 involved is a little complex):
193
194 .. code-block:: pycon
195
196 >>> Article.objects.exclude(publications=p2)
197 <QuerySet [<Article: Django lets you build web apps easily>]>
198
199 If we delete a ``Publication``, its related ``Article`` instances won't be able
200 to access it:
201
202 .. code-block:: pycon
203
204 >>> p1.delete()
205 >>> Publication.objects.all()
206 <QuerySet [<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>]>
207 >>> a1 = Article.objects.get(pk=1)
208 >>> a1.publications.all()
209 <QuerySet []>
210
211 If we delete an ``Article``, its related ``Publication`` instances won't be
212 able to access it:
213
214 .. code-block:: pycon
215
216 >>> a2.delete()
217 >>> Article.objects.all()
218 <QuerySet [<Article: Django lets you build web apps easily>]>
219 >>> p2.article_set.all()
220 <QuerySet []>
221
222 Adding via the 'other' end of an m2m:
223
224 .. code-block:: pycon
225
226 >>> a4 = Article(headline="NASA finds intelligent life on Earth")
227 >>> a4.save()
228 >>> p2.article_set.add(a4)
229 >>> p2.article_set.all()
230 <QuerySet [<Article: NASA finds intelligent life on Earth>]>
231 >>> a4.publications.all()
232 <QuerySet [<Publication: Science News>]>
233
234 Adding via the other end using keywords:
235
236 .. code-block:: pycon
237
238 >>> new_article = p2.article_set.create(headline="Oxygen-free diet works wonders")
239 >>> p2.article_set.all()
240 <QuerySet [<Article: NASA finds intelligent life on Earth>, <Article: Oxygen-free diet works wonders>]>
241 >>> a5 = p2.article_set.all()[1]
242 >>> a5.publications.all()
243 <QuerySet [<Publication: Science News>]>
244
245 Removing ``Publication`` from an ``Article``:
246
247 .. code-block:: pycon
248
249 >>> a4.publications.remove(p2)
250 >>> p2.article_set.all()
251 <QuerySet [<Article: Oxygen-free diet works wonders>]>
252 >>> a4.publications.all()
253 <QuerySet []>
254
255 And from the other end:
256
257 .. code-block:: pycon
258
259 >>> p2.article_set.remove(a5)
260 >>> p2.article_set.all()
261 <QuerySet []>
262 >>> a5.publications.all()
263 <QuerySet []>
264
265 Relation sets can be set:
266
267 .. code-block:: pycon
268
269 >>> a4.publications.all()
270 <QuerySet [<Publication: Science News>]>
271 >>> a4.publications.set([p3])
272 >>> a4.publications.all()
273 <QuerySet [<Publication: Science Weekly>]>
274
275 Relation sets can be cleared:
276
277 .. code-block:: pycon
278
279 >>> p2.article_set.clear()
280 >>> p2.article_set.all()
281 <QuerySet []>
282
283 And you can clear from the other end:
284
285 .. code-block:: pycon
286
287 >>> p2.article_set.add(a4, a5)
288 >>> p2.article_set.all()
289 <QuerySet [<Article: NASA finds intelligent life on Earth>, <Article: Oxygen-free diet works wonders>]>
290 >>> a4.publications.all()
291 <QuerySet [<Publication: Science News>, <Publication: Science Weekly>]>
292 >>> a4.publications.clear()
293 >>> a4.publications.all()
294 <QuerySet []>
295 >>> p2.article_set.all()
296 <QuerySet [<Article: Oxygen-free diet works wonders>]>
297
298 Recreate the ``Article`` and ``Publication`` we have deleted:
299
300 .. code-block:: pycon
301
302 >>> p1 = Publication(title="The Python Journal")
303 >>> p1.save()
304 >>> a2 = Article(headline="NASA uses Python")
305 >>> a2.save()
306 >>> a2.publications.add(p1, p2, p3)
307
308 Bulk delete some ``Publication`` instances, and the references to deleted
309 publications will no longer be included in the related entries:
310
311 .. code-block:: pycon
312
313 >>> Publication.objects.filter(title__startswith="Science").delete()
314 >>> Publication.objects.all()
315 <QuerySet [<Publication: Highlights for Children>, <Publication: The Python Journal>]>
316 >>> Article.objects.all()
317 <QuerySet [<Article: Django lets you build web apps easily>, <Article: NASA finds intelligent life on Earth>, <Article: NASA uses Python>, <Article: Oxygen-free diet works wonders>]>
318 >>> a2.publications.all()
319 <QuerySet [<Publication: The Python Journal>]>
320
321 Bulk delete some articles - references to deleted objects should go:
322
323 .. code-block:: pycon
324
325 >>> q = Article.objects.filter(headline__startswith="Django")
326 >>> print(q)
327 <QuerySet [<Article: Django lets you build web apps easily>]>
328 >>> q.delete()
329
330 After the :meth:`~django.db.models.query.QuerySet.delete`, the
331 :class:`~django.db.models.query.QuerySet` cache needs to be cleared, and the
332 referenced objects should be gone:
333
334 .. code-block:: pycon
335
336 >>> print(q)
337 <QuerySet []>
338 >>> p1.article_set.all()
339 <QuerySet [<Article: NASA uses Python>]>