Django

Code

root/django/trunk/tests/modeltests/many_to_many/models.py

Revision 8325, 9.5 kB (checked in by gwilson, 4 weeks ago)

Fixed a couple typos in the modeltests' descriptions and made use of ReST inline literal markup for code snippets.

  • Property svn:eol-style set to native
Line 
1 """
2 5. Many-to-many relationships
3
4 To define a many-to-many relationship, use ``ManyToManyField()``.
5
6 In this example, an ``Article`` can be published in multiple ``Publication``
7 objects, and a ``Publication`` has multiple ``Article`` objects.
8 """
9
10 from django.db import models
11
12 class Publication(models.Model):
13     title = models.CharField(max_length=30)
14
15     def __unicode__(self):
16         return self.title
17
18     class Meta:
19         ordering = ('title',)
20
21 class Article(models.Model):
22     headline = models.CharField(max_length=100)
23     publications = models.ManyToManyField(Publication)
24
25     def __unicode__(self):
26         return self.headline
27
28     class Meta:
29         ordering = ('headline',)
30
31 __test__ = {'API_TESTS':"""
32 # Create a couple of Publications.
33 >>> p1 = Publication(id=None, title='The Python Journal')
34 >>> p1.save()
35 >>> p2 = Publication(id=None, title='Science News')
36 >>> p2.save()
37 >>> p3 = Publication(id=None, title='Science Weekly')
38 >>> p3.save()
39
40 # Create an Article.
41 >>> a1 = Article(id=None, headline='Django lets you build Web apps easily')
42
43 # You can't associate it with a Publication until it's been saved.
44 >>> a1.publications.add(p1)
45 Traceback (most recent call last):
46 ...
47 ValueError: 'Article' instance needs to have a primary key value before a many-to-many relationship can be used.
48
49 # Save it!
50 >>> a1.save()
51
52 # Associate the Article with a Publication.
53 >>> a1.publications.add(p1)
54
55 # Create another Article, and set it to appear in both Publications.
56 >>> a2 = Article(id=None, headline='NASA uses Python')
57 >>> a2.save()
58 >>> a2.publications.add(p1, p2)
59 >>> a2.publications.add(p3)
60
61 # Adding a second time is OK
62 >>> a2.publications.add(p3)
63
64 # Add a Publication directly via publications.add by using keyword arguments.
65 >>> new_publication = a2.publications.create(title='Highlights for Children')
66
67 # Article objects have access to their related Publication objects.
68 >>> a1.publications.all()
69 [<Publication: The Python Journal>]
70 >>> a2.publications.all()
71 [<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>, <Publication: The Python Journal>]
72
73 # Publication objects have access to their related Article objects.
74 >>> p2.article_set.all()
75 [<Article: NASA uses Python>]
76 >>> p1.article_set.all()
77 [<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]
78 >>> Publication.objects.get(id=4).article_set.all()
79 [<Article: NASA uses Python>]
80
81 # We can perform kwarg queries across m2m relationships
82 >>> Article.objects.filter(publications__id__exact=1)
83 [<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]
84 >>> Article.objects.filter(publications__pk=1)
85 [<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]
86 >>> Article.objects.filter(publications=1)
87 [<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]
88 >>> Article.objects.filter(publications=p1)
89 [<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]
90
91 >>> Article.objects.filter(publications__title__startswith="Science")
92 [<Article: NASA uses Python>, <Article: NASA uses Python>]
93
94 >>> Article.objects.filter(publications__title__startswith="Science").distinct()
95 [<Article: NASA uses Python>]
96
97 # The count() function respects distinct() as well.
98 >>> Article.objects.filter(publications__title__startswith="Science").count()
99 2
100
101 >>> Article.objects.filter(publications__title__startswith="Science").distinct().count()
102 1
103
104 >>> Article.objects.filter(publications__in=[1,2]).distinct()
105 [<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]
106 >>> Article.objects.filter(publications__in=[1,p2]).distinct()
107 [<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]
108 >>> Article.objects.filter(publications__in=[p1,p2]).distinct()
109 [<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]
110
111 # Reverse m2m queries are supported (i.e., starting at the table that doesn't
112 # have a ManyToManyField).
113 >>> Publication.objects.filter(id__exact=1)
114 [<Publication: The Python Journal>]
115 >>> Publication.objects.filter(pk=1)
116 [<Publication: The Python Journal>]
117
118 >>> Publication.objects.filter(article__headline__startswith="NASA")
119 [<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>, <Publication: The Python Journal>]
120
121 >>> Publication.objects.filter(article__id__exact=1)
122 [<Publication: The Python Journal>]
123 >>> Publication.objects.filter(article__pk=1)
124 [<Publication: The Python Journal>]
125 >>> Publication.objects.filter(article=1)
126 [<Publication: The Python Journal>]
127 >>> Publication.objects.filter(article=a1)
128 [<Publication: The Python Journal>]
129
130 >>> Publication.objects.filter(article__in=[1,2]).distinct()
131 [<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>, <Publication: The Python Journal>]
132 >>> Publication.objects.filter(article__in=[1,a2]).distinct()
133 [<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>, <Publication: The Python Journal>]
134 >>> Publication.objects.filter(article__in=[a1,a2]).distinct()
135 [<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>, <Publication: The Python Journal>]
136
137 # Excluding a related item works as you would expect, too (although the SQL
138 # involved is a little complex).
139 >>> Article.objects.exclude(publications=p2)
140 [<Article: Django lets you build Web apps easily>]
141
142 # If we delete a Publication, its Articles won't be able to access it.
143 >>> p1.delete()
144 >>> Publication.objects.all()
145 [<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>]
146 >>> a1 = Article.objects.get(pk=1)
147 >>> a1.publications.all()
148 []
149
150 # If we delete an Article, its Publications won't be able to access it.
151 >>> a2.delete()
152 >>> Article.objects.all()
153 [<Article: Django lets you build Web apps easily>]
154 >>> p2.article_set.all()
155 []
156
157 # Adding via the 'other' end of an m2m
158 >>> a4 = Article(headline='NASA finds intelligent life on Earth')
159 >>> a4.save()
160 >>> p2.article_set.add(a4)
161 >>> p2.article_set.all()
162 [<Article: NASA finds intelligent life on Earth>]
163 >>> a4.publications.all()
164 [<Publication: Science News>]
165
166 # Adding via the other end using keywords
167 >>> new_article = p2.article_set.create(headline='Oxygen-free diet works wonders')
168 >>> p2.article_set.all()
169 [<Article: NASA finds intelligent life on Earth>, <Article: Oxygen-free diet works wonders>]
170 >>> a5 = p2.article_set.all()[1]
171 >>> a5.publications.all()
172 [<Publication: Science News>]
173
174 # Removing publication from an article:
175 >>> a4.publications.remove(p2)
176 >>> p2.article_set.all()
177 [<Article: Oxygen-free diet works wonders>]
178 >>> a4.publications.all()
179 []
180
181 # And from the other end
182 >>> p2.article_set.remove(a5)
183 >>> p2.article_set.all()
184 []
185 >>> a5.publications.all()
186 []
187
188 # Relation sets can be assigned. Assignment clears any existing set members
189 >>> p2.article_set = [a4, a5]
190 >>> p2.article_set.all()
191 [<Article: NASA finds intelligent life on Earth>, <Article: Oxygen-free diet works wonders>]
192 >>> a4.publications.all()
193 [<Publication: Science News>]
194 >>> a4.publications = [p3]
195 >>> p2.article_set.all()
196 [<Article: Oxygen-free diet works wonders>]
197 >>> a4.publications.all()
198 [<Publication: Science Weekly>]
199
200 # Relation sets can be cleared:
201 >>> p2.article_set.clear()
202 >>> p2.article_set.all()
203 []
204 >>> a4.publications.all()
205 [<Publication: Science Weekly>]
206
207 # And you can clear from the other end
208 >>> p2.article_set.add(a4, a5)
209 >>> p2.article_set.all()
210 [<Article: NASA finds intelligent life on Earth>, <Article: Oxygen-free diet works wonders>]
211 >>> a4.publications.all()
212 [<Publication: Science News>, <Publication: Science Weekly>]
213 >>> a4.publications.clear()
214 >>> a4.publications.all()
215 []
216 >>> p2.article_set.all()
217 [<Article: Oxygen-free diet works wonders>]
218
219 # Relation sets can also be set using primary key values
220 >>> p2.article_set = [a4.id, a5.id]
221 >>> p2.article_set.all()
222 [<Article: NASA finds intelligent life on Earth>, <Article: Oxygen-free diet works wonders>]
223 >>> a4.publications.all()
224 [<Publication: Science News>]
225 >>> a4.publications = [p3.id]
226 >>> p2.article_set.all()
227 [<Article: Oxygen-free diet works wonders>]
228 >>> a4.publications.all()
229 [<Publication: Science Weekly>]
230
231 # Recreate the article and Publication we have deleted.
232 >>> p1 = Publication(id=None, title='The Python Journal')
233 >>> p1.save()
234 >>> a2 = Article(id=None, headline='NASA uses Python')
235 >>> a2.save()
236 >>> a2.publications.add(p1, p2, p3)
237
238 # Bulk delete some Publications - references to deleted publications should go
239 >>> Publication.objects.filter(title__startswith='Science').delete()
240 >>> Publication.objects.all()
241 [<Publication: Highlights for Children>, <Publication: The Python Journal>]
242 >>> Article.objects.all()
243 [<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>]
244 >>> a2.publications.all()
245 [<Publication: The Python Journal>]
246
247 # Bulk delete some articles - references to deleted objects should go
248 >>> q = Article.objects.filter(headline__startswith='Django')
249 >>> print q
250 [<Article: Django lets you build Web apps easily>]
251 >>> q.delete()
252
253 # After the delete, the QuerySet cache needs to be cleared, and the referenced objects should be gone
254 >>> print q
255 []
256 >>> p1.article_set.all()
257 [<Article: NASA uses Python>]
258
259 # An alternate to calling clear() is to assign the empty set
260 >>> p1.article_set = []
261 >>> p1.article_set.all()
262 []
263
264 >>> a2.publications = [p1, new_publication]
265 >>> a2.publications.all()
266 [<Publication: Highlights for Children>, <Publication: The Python Journal>]
267 >>> a2.publications = []
268 >>> a2.publications.all()
269 []
270
271 """}
Note: See TracBrowser for help on using the browser.