many_to_many.txt 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. ==========================
  2. Many-to-many relationships
  3. ==========================
  4. To define a many-to-many relationship, use
  5. :class:`~django.db.models.ManyToManyField`.
  6. In this example, an ``Article`` can be published in multiple ``Publication``
  7. objects, and a ``Publication`` has multiple ``Article`` objects:
  8. .. code-block:: python
  9. from django.db import models
  10. class Publication(models.Model):
  11. title = models.CharField(max_length=30)
  12. class Meta:
  13. ordering = ["title"]
  14. def __str__(self):
  15. return self.title
  16. class Article(models.Model):
  17. headline = models.CharField(max_length=100)
  18. publications = models.ManyToManyField(Publication)
  19. class Meta:
  20. ordering = ["headline"]
  21. def __str__(self):
  22. return self.headline
  23. What follows are examples of operations that can be performed using the Python
  24. API facilities.
  25. Create a few ``Publications``:
  26. .. code-block:: pycon
  27. >>> p1 = Publication(title="The Python Journal")
  28. >>> p1.save()
  29. >>> p2 = Publication(title="Science News")
  30. >>> p2.save()
  31. >>> p3 = Publication(title="Science Weekly")
  32. >>> p3.save()
  33. Create an ``Article``:
  34. .. code-block:: pycon
  35. >>> a1 = Article(headline="Django lets you build web apps easily")
  36. You can't associate it with a ``Publication`` until it's been saved:
  37. .. code-block:: pycon
  38. >>> a1.publications.add(p1)
  39. Traceback (most recent call last):
  40. ...
  41. 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.
  42. Save it!
  43. .. code-block:: pycon
  44. >>> a1.save()
  45. Associate the ``Article`` with a ``Publication``:
  46. .. code-block:: pycon
  47. >>> a1.publications.add(p1)
  48. Create another ``Article``, and set it to appear in the ``Publications``:
  49. .. code-block:: pycon
  50. >>> a2 = Article(headline="NASA uses Python")
  51. >>> a2.save()
  52. >>> a2.publications.add(p1, p2)
  53. >>> a2.publications.add(p3)
  54. Adding a second time is OK, it will not duplicate the relation:
  55. .. code-block:: pycon
  56. >>> a2.publications.add(p3)
  57. Adding an object of the wrong type raises :exc:`TypeError`:
  58. .. code-block:: pycon
  59. >>> a2.publications.add(a1)
  60. Traceback (most recent call last):
  61. ...
  62. TypeError: 'Publication' instance expected
  63. Create and add a ``Publication`` to an ``Article`` in one step using
  64. :meth:`~django.db.models.fields.related.RelatedManager.create`:
  65. .. code-block:: pycon
  66. >>> new_publication = a2.publications.create(title="Highlights for Children")
  67. ``Article`` objects have access to their related ``Publication`` objects:
  68. .. code-block:: pycon
  69. >>> a1.publications.all()
  70. <QuerySet [<Publication: The Python Journal>]>
  71. >>> a2.publications.all()
  72. <QuerySet [<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>, <Publication: The Python Journal>]>
  73. ``Publication`` objects have access to their related ``Article`` objects:
  74. .. code-block:: pycon
  75. >>> p2.article_set.all()
  76. <QuerySet [<Article: NASA uses Python>]>
  77. >>> p1.article_set.all()
  78. <QuerySet [<Article: Django lets you build web apps easily>, <Article: NASA uses Python>]>
  79. >>> Publication.objects.get(id=4).article_set.all()
  80. <QuerySet [<Article: NASA uses Python>]>
  81. Many-to-many relationships can be queried using :ref:`lookups across
  82. relationships <lookups-that-span-relationships>`:
  83. .. code-block:: pycon
  84. >>> Article.objects.filter(publications__id=1)
  85. <QuerySet [<Article: Django lets you build web apps easily>, <Article: NASA uses Python>]>
  86. >>> Article.objects.filter(publications__pk=1)
  87. <QuerySet [<Article: Django lets you build web apps easily>, <Article: NASA uses Python>]>
  88. >>> Article.objects.filter(publications=1)
  89. <QuerySet [<Article: Django lets you build web apps easily>, <Article: NASA uses Python>]>
  90. >>> Article.objects.filter(publications=p1)
  91. <QuerySet [<Article: Django lets you build web apps easily>, <Article: NASA uses Python>]>
  92. >>> Article.objects.filter(publications__title__startswith="Science")
  93. <QuerySet [<Article: NASA uses Python>, <Article: NASA uses Python>]>
  94. >>> Article.objects.filter(publications__title__startswith="Science").distinct()
  95. <QuerySet [<Article: NASA uses Python>]>
  96. The :meth:`~django.db.models.query.QuerySet.count` function respects
  97. :meth:`~django.db.models.query.QuerySet.distinct` as well:
  98. .. code-block:: pycon
  99. >>> Article.objects.filter(publications__title__startswith="Science").count()
  100. 2
  101. >>> Article.objects.filter(publications__title__startswith="Science").distinct().count()
  102. 1
  103. >>> Article.objects.filter(publications__in=[1, 2]).distinct()
  104. <QuerySet [<Article: Django lets you build web apps easily>, <Article: NASA uses Python>]>
  105. >>> Article.objects.filter(publications__in=[p1, p2]).distinct()
  106. <QuerySet [<Article: Django lets you build web apps easily>, <Article: NASA uses Python>]>
  107. Reverse m2m queries are supported (i.e., starting at the table that doesn't have
  108. a :class:`~django.db.models.ManyToManyField`):
  109. .. code-block:: pycon
  110. >>> Publication.objects.filter(id=1)
  111. <QuerySet [<Publication: The Python Journal>]>
  112. >>> Publication.objects.filter(pk=1)
  113. <QuerySet [<Publication: The Python Journal>]>
  114. >>> Publication.objects.filter(article__headline__startswith="NASA")
  115. <QuerySet [<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>, <Publication: The Python Journal>]>
  116. >>> Publication.objects.filter(article__id=1)
  117. <QuerySet [<Publication: The Python Journal>]>
  118. >>> Publication.objects.filter(article__pk=1)
  119. <QuerySet [<Publication: The Python Journal>]>
  120. >>> Publication.objects.filter(article=1)
  121. <QuerySet [<Publication: The Python Journal>]>
  122. >>> Publication.objects.filter(article=a1)
  123. <QuerySet [<Publication: The Python Journal>]>
  124. >>> Publication.objects.filter(article__in=[1, 2]).distinct()
  125. <QuerySet [<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>, <Publication: The Python Journal>]>
  126. >>> Publication.objects.filter(article__in=[a1, a2]).distinct()
  127. <QuerySet [<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>, <Publication: The Python Journal>]>
  128. Excluding a related item works as you would expect, too (although the SQL
  129. involved is a little complex):
  130. .. code-block:: pycon
  131. >>> Article.objects.exclude(publications=p2)
  132. <QuerySet [<Article: Django lets you build web apps easily>]>
  133. If we delete a ``Publication``, its ``Articles`` won't be able to access it:
  134. .. code-block:: pycon
  135. >>> p1.delete()
  136. >>> Publication.objects.all()
  137. <QuerySet [<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>]>
  138. >>> a1 = Article.objects.get(pk=1)
  139. >>> a1.publications.all()
  140. <QuerySet []>
  141. If we delete an ``Article``, its ``Publications`` won't be able to access it:
  142. .. code-block:: pycon
  143. >>> a2.delete()
  144. >>> Article.objects.all()
  145. <QuerySet [<Article: Django lets you build web apps easily>]>
  146. >>> p2.article_set.all()
  147. <QuerySet []>
  148. Adding via the 'other' end of an m2m:
  149. .. code-block:: pycon
  150. >>> a4 = Article(headline="NASA finds intelligent life on Earth")
  151. >>> a4.save()
  152. >>> p2.article_set.add(a4)
  153. >>> p2.article_set.all()
  154. <QuerySet [<Article: NASA finds intelligent life on Earth>]>
  155. >>> a4.publications.all()
  156. <QuerySet [<Publication: Science News>]>
  157. Adding via the other end using keywords:
  158. .. code-block:: pycon
  159. >>> new_article = p2.article_set.create(headline="Oxygen-free diet works wonders")
  160. >>> p2.article_set.all()
  161. <QuerySet [<Article: NASA finds intelligent life on Earth>, <Article: Oxygen-free diet works wonders>]>
  162. >>> a5 = p2.article_set.all()[1]
  163. >>> a5.publications.all()
  164. <QuerySet [<Publication: Science News>]>
  165. Removing ``Publication`` from an ``Article``:
  166. .. code-block:: pycon
  167. >>> a4.publications.remove(p2)
  168. >>> p2.article_set.all()
  169. <QuerySet [<Article: Oxygen-free diet works wonders>]>
  170. >>> a4.publications.all()
  171. <QuerySet []>
  172. And from the other end:
  173. .. code-block:: pycon
  174. >>> p2.article_set.remove(a5)
  175. >>> p2.article_set.all()
  176. <QuerySet []>
  177. >>> a5.publications.all()
  178. <QuerySet []>
  179. Relation sets can be set:
  180. .. code-block:: pycon
  181. >>> a4.publications.all()
  182. <QuerySet [<Publication: Science News>]>
  183. >>> a4.publications.set([p3])
  184. >>> a4.publications.all()
  185. <QuerySet [<Publication: Science Weekly>]>
  186. Relation sets can be cleared:
  187. .. code-block:: pycon
  188. >>> p2.article_set.clear()
  189. >>> p2.article_set.all()
  190. <QuerySet []>
  191. And you can clear from the other end:
  192. .. code-block:: pycon
  193. >>> p2.article_set.add(a4, a5)
  194. >>> p2.article_set.all()
  195. <QuerySet [<Article: NASA finds intelligent life on Earth>, <Article: Oxygen-free diet works wonders>]>
  196. >>> a4.publications.all()
  197. <QuerySet [<Publication: Science News>, <Publication: Science Weekly>]>
  198. >>> a4.publications.clear()
  199. >>> a4.publications.all()
  200. <QuerySet []>
  201. >>> p2.article_set.all()
  202. <QuerySet [<Article: Oxygen-free diet works wonders>]>
  203. Recreate the ``Article`` and ``Publication`` we have deleted:
  204. .. code-block:: pycon
  205. >>> p1 = Publication(title="The Python Journal")
  206. >>> p1.save()
  207. >>> a2 = Article(headline="NASA uses Python")
  208. >>> a2.save()
  209. >>> a2.publications.add(p1, p2, p3)
  210. Bulk delete some ``Publications`` - references to deleted publications should
  211. go:
  212. .. code-block:: pycon
  213. >>> Publication.objects.filter(title__startswith="Science").delete()
  214. >>> Publication.objects.all()
  215. <QuerySet [<Publication: Highlights for Children>, <Publication: The Python Journal>]>
  216. >>> Article.objects.all()
  217. <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>]>
  218. >>> a2.publications.all()
  219. <QuerySet [<Publication: The Python Journal>]>
  220. Bulk delete some articles - references to deleted objects should go:
  221. .. code-block:: pycon
  222. >>> q = Article.objects.filter(headline__startswith="Django")
  223. >>> print(q)
  224. <QuerySet [<Article: Django lets you build web apps easily>]>
  225. >>> q.delete()
  226. After the :meth:`~django.db.models.query.QuerySet.delete`, the
  227. :class:`~django.db.models.query.QuerySet` cache needs to be cleared, and the
  228. referenced objects should be gone:
  229. .. code-block:: pycon
  230. >>> print(q)
  231. <QuerySet []>
  232. >>> p1.article_set.all()
  233. <QuerySet [<Article: NASA uses Python>]>