many_to_many.txt 9.9 KB

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