2
0

many_to_many.txt 9.8 KB

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