many_to_many.txt 9.5 KB

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