many_to_many.txt 10 KB

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