many_to_many.txt 11 KB

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