/packages/Django/tests/modeltests/many_to_many/models.py

https://github.com/lmorchard/home-snippets-server-lib · Python · 277 lines · 261 code · 8 blank · 8 comment · 0 complexity · 2319d645200e9a7eeaff0fb69f45eae2 MD5 · raw file

  1. """
  2. 5. Many-to-many relationships
  3. To define a many-to-many relationship, use ``ManyToManyField()``.
  4. In this example, an ``Article`` can be published in multiple ``Publication``
  5. objects, and a ``Publication`` has multiple ``Article`` objects.
  6. """
  7. from django.db import models
  8. class Publication(models.Model):
  9. title = models.CharField(max_length=30)
  10. def __unicode__(self):
  11. return self.title
  12. class Meta:
  13. ordering = ('title',)
  14. class Article(models.Model):
  15. headline = models.CharField(max_length=100)
  16. publications = models.ManyToManyField(Publication)
  17. def __unicode__(self):
  18. return self.headline
  19. class Meta:
  20. ordering = ('headline',)
  21. __test__ = {'API_TESTS':"""
  22. # Create a couple of Publications.
  23. >>> p1 = Publication(id=None, title='The Python Journal')
  24. >>> p1.save()
  25. >>> p2 = Publication(id=None, title='Science News')
  26. >>> p2.save()
  27. >>> p3 = Publication(id=None, title='Science Weekly')
  28. >>> p3.save()
  29. # Create an Article.
  30. >>> a1 = Article(id=None, headline='Django lets you build Web apps easily')
  31. # You can't associate it with a Publication until it's been saved.
  32. >>> a1.publications.add(p1)
  33. Traceback (most recent call last):
  34. ...
  35. ValueError: 'Article' instance needs to have a primary key value before a many-to-many relationship can be used.
  36. # Save it!
  37. >>> a1.save()
  38. # Associate the Article with a Publication.
  39. >>> a1.publications.add(p1)
  40. # Create another Article, and set it to appear in both Publications.
  41. >>> a2 = Article(id=None, headline='NASA uses Python')
  42. >>> a2.save()
  43. >>> a2.publications.add(p1, p2)
  44. >>> a2.publications.add(p3)
  45. # Adding a second time is OK
  46. >>> a2.publications.add(p3)
  47. # Adding an object of the wrong type raises TypeError
  48. >>> a2.publications.add(a1)
  49. Traceback (most recent call last):
  50. ...
  51. TypeError: 'Publication' instance expected
  52. # Add a Publication directly via publications.add by using keyword arguments.
  53. >>> new_publication = a2.publications.create(title='Highlights for Children')
  54. # Article objects have access to their related Publication objects.
  55. >>> a1.publications.all()
  56. [<Publication: The Python Journal>]
  57. >>> a2.publications.all()
  58. [<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>, <Publication: The Python Journal>]
  59. # Publication objects have access to their related Article objects.
  60. >>> p2.article_set.all()
  61. [<Article: NASA uses Python>]
  62. >>> p1.article_set.all()
  63. [<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]
  64. >>> Publication.objects.get(id=4).article_set.all()
  65. [<Article: NASA uses Python>]
  66. # We can perform kwarg queries across m2m relationships
  67. >>> Article.objects.filter(publications__id__exact=1)
  68. [<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]
  69. >>> Article.objects.filter(publications__pk=1)
  70. [<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]
  71. >>> Article.objects.filter(publications=1)
  72. [<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]
  73. >>> Article.objects.filter(publications=p1)
  74. [<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]
  75. >>> Article.objects.filter(publications__title__startswith="Science")
  76. [<Article: NASA uses Python>, <Article: NASA uses Python>]
  77. >>> Article.objects.filter(publications__title__startswith="Science").distinct()
  78. [<Article: NASA uses Python>]
  79. # The count() function respects distinct() as well.
  80. >>> Article.objects.filter(publications__title__startswith="Science").count()
  81. 2
  82. >>> Article.objects.filter(publications__title__startswith="Science").distinct().count()
  83. 1
  84. >>> Article.objects.filter(publications__in=[1,2]).distinct()
  85. [<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]
  86. >>> Article.objects.filter(publications__in=[1,p2]).distinct()
  87. [<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]
  88. >>> Article.objects.filter(publications__in=[p1,p2]).distinct()
  89. [<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]
  90. # Reverse m2m queries are supported (i.e., starting at the table that doesn't
  91. # have a ManyToManyField).
  92. >>> Publication.objects.filter(id__exact=1)
  93. [<Publication: The Python Journal>]
  94. >>> Publication.objects.filter(pk=1)
  95. [<Publication: The Python Journal>]
  96. >>> Publication.objects.filter(article__headline__startswith="NASA")
  97. [<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>, <Publication: The Python Journal>]
  98. >>> Publication.objects.filter(article__id__exact=1)
  99. [<Publication: The Python Journal>]
  100. >>> Publication.objects.filter(article__pk=1)
  101. [<Publication: The Python Journal>]
  102. >>> Publication.objects.filter(article=1)
  103. [<Publication: The Python Journal>]
  104. >>> Publication.objects.filter(article=a1)
  105. [<Publication: The Python Journal>]
  106. >>> Publication.objects.filter(article__in=[1,2]).distinct()
  107. [<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>, <Publication: The Python Journal>]
  108. >>> Publication.objects.filter(article__in=[1,a2]).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. >>> p2.article_set = [a4, a5]
  158. >>> p2.article_set.all()
  159. [<Article: NASA finds intelligent life on Earth>, <Article: Oxygen-free diet works wonders>]
  160. >>> a4.publications.all()
  161. [<Publication: Science News>]
  162. >>> a4.publications = [p3]
  163. >>> p2.article_set.all()
  164. [<Article: Oxygen-free diet works wonders>]
  165. >>> a4.publications.all()
  166. [<Publication: Science Weekly>]
  167. # Relation sets can be cleared:
  168. >>> p2.article_set.clear()
  169. >>> p2.article_set.all()
  170. []
  171. >>> a4.publications.all()
  172. [<Publication: Science Weekly>]
  173. # And you can clear from the other end
  174. >>> p2.article_set.add(a4, a5)
  175. >>> p2.article_set.all()
  176. [<Article: NASA finds intelligent life on Earth>, <Article: Oxygen-free diet works wonders>]
  177. >>> a4.publications.all()
  178. [<Publication: Science News>, <Publication: Science Weekly>]
  179. >>> a4.publications.clear()
  180. >>> a4.publications.all()
  181. []
  182. >>> p2.article_set.all()
  183. [<Article: Oxygen-free diet works wonders>]
  184. # Relation sets can also be set using primary key values
  185. >>> p2.article_set = [a4.id, a5.id]
  186. >>> p2.article_set.all()
  187. [<Article: NASA finds intelligent life on Earth>, <Article: Oxygen-free diet works wonders>]
  188. >>> a4.publications.all()
  189. [<Publication: Science News>]
  190. >>> a4.publications = [p3.id]
  191. >>> p2.article_set.all()
  192. [<Article: Oxygen-free diet works wonders>]
  193. >>> a4.publications.all()
  194. [<Publication: Science Weekly>]
  195. # Recreate the article and Publication we have deleted.
  196. >>> p1 = Publication(id=None, title='The Python Journal')
  197. >>> p1.save()
  198. >>> a2 = Article(id=None, headline='NASA uses Python')
  199. >>> a2.save()
  200. >>> a2.publications.add(p1, p2, p3)
  201. # Bulk delete some Publications - references to deleted publications should go
  202. >>> Publication.objects.filter(title__startswith='Science').delete()
  203. >>> Publication.objects.all()
  204. [<Publication: Highlights for Children>, <Publication: The Python Journal>]
  205. >>> Article.objects.all()
  206. [<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>]
  207. >>> a2.publications.all()
  208. [<Publication: The Python Journal>]
  209. # Bulk delete some articles - references to deleted objects should go
  210. >>> q = Article.objects.filter(headline__startswith='Django')
  211. >>> print q
  212. [<Article: Django lets you build Web apps easily>]
  213. >>> q.delete()
  214. # After the delete, the QuerySet cache needs to be cleared, and the referenced objects should be gone
  215. >>> print q
  216. []
  217. >>> p1.article_set.all()
  218. [<Article: NASA uses Python>]
  219. # An alternate to calling clear() is to assign the empty set
  220. >>> p1.article_set = []
  221. >>> p1.article_set.all()
  222. []
  223. >>> a2.publications = [p1, new_publication]
  224. >>> a2.publications.all()
  225. [<Publication: Highlights for Children>, <Publication: The Python Journal>]
  226. >>> a2.publications = []
  227. >>> a2.publications.all()
  228. []
  229. """}