Merged the queryset-refactor branch into trunk.
[fdr-django.git] / tests / modeltests / basic / models.py
blob51de8a50f8685063def18b44136b121d6667f461
1 # coding: utf-8
2 """
3 1. Bare-bones model
5 This is a basic model with only two non-primary-key fields.
6 """
8 try:
9 set
10 except NameError:
11 from sets import Set as set
13 from django.db import models
15 class Article(models.Model):
16 headline = models.CharField(max_length=100, default='Default headline')
17 pub_date = models.DateTimeField()
19 class Meta:
20 ordering = ('pub_date','headline')
22 def __unicode__(self):
23 return self.headline
25 __test__ = {'API_TESTS': """
26 # No articles are in the system yet.
27 >>> Article.objects.all()
30 # Create an Article.
31 >>> from datetime import datetime
32 >>> a = Article(id=None, headline='Area man programs in Python', pub_date=datetime(2005, 7, 28))
34 # Save it into the database. You have to call save() explicitly.
35 >>> a.save()
37 # Now it has an ID. Note it's a long integer, as designated by the trailing "L".
38 >>> a.id
41 # Models have a pk property that is an alias for the primary key attribute (by
42 # default, the 'id' attribute).
43 >>> a.pk
46 # Access database columns via Python attributes.
47 >>> a.headline
48 'Area man programs in Python'
49 >>> a.pub_date
50 datetime.datetime(2005, 7, 28, 0, 0)
52 # Change values by changing the attributes, then calling save().
53 >>> a.headline = 'Area woman programs in Python'
54 >>> a.save()
56 # Article.objects.all() returns all the articles in the database.
57 >>> Article.objects.all()
58 [<Article: Area woman programs in Python>]
60 # Django provides a rich database lookup API.
61 >>> Article.objects.get(id__exact=1)
62 <Article: Area woman programs in Python>
63 >>> Article.objects.get(headline__startswith='Area woman')
64 <Article: Area woman programs in Python>
65 >>> Article.objects.get(pub_date__year=2005)
66 <Article: Area woman programs in Python>
67 >>> Article.objects.get(pub_date__year=2005, pub_date__month=7)
68 <Article: Area woman programs in Python>
69 >>> Article.objects.get(pub_date__year=2005, pub_date__month=7, pub_date__day=28)
70 <Article: Area woman programs in Python>
72 # The "__exact" lookup type can be omitted, as a shortcut.
73 >>> Article.objects.get(id=1)
74 <Article: Area woman programs in Python>
75 >>> Article.objects.get(headline='Area woman programs in Python')
76 <Article: Area woman programs in Python>
78 >>> Article.objects.filter(pub_date__year=2005)
79 [<Article: Area woman programs in Python>]
80 >>> Article.objects.filter(pub_date__year=2004)
82 >>> Article.objects.filter(pub_date__year=2005, pub_date__month=7)
83 [<Article: Area woman programs in Python>]
85 # Django raises an Article.DoesNotExist exception for get() if the parameters
86 # don't match any object.
87 >>> Article.objects.get(id__exact=2)
88 Traceback (most recent call last):
89 ...
90 DoesNotExist: Article matching query does not exist.
92 >>> Article.objects.get(pub_date__year=2005, pub_date__month=8)
93 Traceback (most recent call last):
94 ...
95 DoesNotExist: Article matching query does not exist.
97 # Lookup by a primary key is the most common case, so Django provides a
98 # shortcut for primary-key exact lookups.
99 # The following is identical to articles.get(id=1).
100 >>> Article.objects.get(pk=1)
101 <Article: Area woman programs in Python>
103 # pk can be used as a shortcut for the primary key name in any query
104 >>> Article.objects.filter(pk__in=[1])
105 [<Article: Area woman programs in Python>]
107 # Model instances of the same type and same ID are considered equal.
108 >>> a = Article.objects.get(pk=1)
109 >>> b = Article.objects.get(pk=1)
110 >>> a == b
111 True
113 # You can initialize a model instance using positional arguments, which should
114 # match the field order as defined in the model.
115 >>> a2 = Article(None, 'Second article', datetime(2005, 7, 29))
116 >>> a2.save()
117 >>> a2.id
119 >>> a2.headline
120 'Second article'
121 >>> a2.pub_date
122 datetime.datetime(2005, 7, 29, 0, 0)
124 # ...or, you can use keyword arguments.
125 >>> a3 = Article(id=None, headline='Third article', pub_date=datetime(2005, 7, 30))
126 >>> a3.save()
127 >>> a3.id
129 >>> a3.headline
130 'Third article'
131 >>> a3.pub_date
132 datetime.datetime(2005, 7, 30, 0, 0)
134 # You can also mix and match position and keyword arguments, but be sure not to
135 # duplicate field information.
136 >>> a4 = Article(None, 'Fourth article', pub_date=datetime(2005, 7, 31))
137 >>> a4.save()
138 >>> a4.headline
139 'Fourth article'
141 # Don't use invalid keyword arguments.
142 >>> a5 = Article(id=None, headline='Invalid', pub_date=datetime(2005, 7, 31), foo='bar')
143 Traceback (most recent call last):
145 TypeError: 'foo' is an invalid keyword argument for this function
147 # You can leave off the value for an AutoField when creating an object, because
148 # it'll get filled in automatically when you save().
149 >>> a5 = Article(headline='Article 6', pub_date=datetime(2005, 7, 31))
150 >>> a5.save()
151 >>> a5.id
153 >>> a5.headline
154 'Article 6'
156 # If you leave off a field with "default" set, Django will use the default.
157 >>> a6 = Article(pub_date=datetime(2005, 7, 31))
158 >>> a6.save()
159 >>> a6.headline
160 u'Default headline'
162 # For DateTimeFields, Django saves as much precision (in seconds) as you
163 # give it.
164 >>> a7 = Article(headline='Article 7', pub_date=datetime(2005, 7, 31, 12, 30))
165 >>> a7.save()
166 >>> Article.objects.get(id__exact=7).pub_date
167 datetime.datetime(2005, 7, 31, 12, 30)
169 >>> a8 = Article(headline='Article 8', pub_date=datetime(2005, 7, 31, 12, 30, 45))
170 >>> a8.save()
171 >>> Article.objects.get(id__exact=8).pub_date
172 datetime.datetime(2005, 7, 31, 12, 30, 45)
173 >>> a8.id
176 # Saving an object again doesn't create a new object -- it just saves the old one.
177 >>> a8.save()
178 >>> a8.id
180 >>> a8.headline = 'Updated article 8'
181 >>> a8.save()
182 >>> a8.id
185 >>> a7 == a8
186 False
187 >>> a8 == Article.objects.get(id__exact=8)
188 True
189 >>> a7 != a8
190 True
191 >>> Article.objects.get(id__exact=8) != Article.objects.get(id__exact=7)
192 True
193 >>> Article.objects.get(id__exact=8) == Article.objects.get(id__exact=7)
194 False
196 # dates() returns a list of available dates of the given scope for the given field.
197 >>> Article.objects.dates('pub_date', 'year')
198 [datetime.datetime(2005, 1, 1, 0, 0)]
199 >>> Article.objects.dates('pub_date', 'month')
200 [datetime.datetime(2005, 7, 1, 0, 0)]
201 >>> Article.objects.dates('pub_date', 'day')
202 [datetime.datetime(2005, 7, 28, 0, 0), datetime.datetime(2005, 7, 29, 0, 0), datetime.datetime(2005, 7, 30, 0, 0), datetime.datetime(2005, 7, 31, 0, 0)]
203 >>> Article.objects.dates('pub_date', 'day', order='ASC')
204 [datetime.datetime(2005, 7, 28, 0, 0), datetime.datetime(2005, 7, 29, 0, 0), datetime.datetime(2005, 7, 30, 0, 0), datetime.datetime(2005, 7, 31, 0, 0)]
205 >>> Article.objects.dates('pub_date', 'day', order='DESC')
206 [datetime.datetime(2005, 7, 31, 0, 0), datetime.datetime(2005, 7, 30, 0, 0), datetime.datetime(2005, 7, 29, 0, 0), datetime.datetime(2005, 7, 28, 0, 0)]
208 # dates() requires valid arguments.
210 >>> Article.objects.dates()
211 Traceback (most recent call last):
213 TypeError: dates() takes at least 3 arguments (1 given)
215 >>> Article.objects.dates('invalid_field', 'year')
216 Traceback (most recent call last):
218 FieldDoesNotExist: Article has no field named 'invalid_field'
220 >>> Article.objects.dates('pub_date', 'bad_kind')
221 Traceback (most recent call last):
223 AssertionError: 'kind' must be one of 'year', 'month' or 'day'.
225 >>> Article.objects.dates('pub_date', 'year', order='bad order')
226 Traceback (most recent call last):
228 AssertionError: 'order' must be either 'ASC' or 'DESC'.
230 # Use iterator() with dates() to return a generator that lazily requests each
231 # result one at a time, to save memory.
232 >>> for a in Article.objects.dates('pub_date', 'day', order='DESC').iterator():
233 ... print repr(a)
234 datetime.datetime(2005, 7, 31, 0, 0)
235 datetime.datetime(2005, 7, 30, 0, 0)
236 datetime.datetime(2005, 7, 29, 0, 0)
237 datetime.datetime(2005, 7, 28, 0, 0)
239 # You can combine queries with & and |.
240 >>> s1 = Article.objects.filter(id__exact=1)
241 >>> s2 = Article.objects.filter(id__exact=2)
242 >>> s1 | s2
243 [<Article: Area woman programs in Python>, <Article: Second article>]
244 >>> s1 & s2
247 # You can get the number of objects like this:
248 >>> len(Article.objects.filter(id__exact=1))
251 # You can get items using index and slice notation.
252 >>> Article.objects.all()[0]
253 <Article: Area woman programs in Python>
254 >>> Article.objects.all()[1:3]
255 [<Article: Second article>, <Article: Third article>]
256 >>> s3 = Article.objects.filter(id__exact=3)
257 >>> (s1 | s2 | s3)[::2]
258 [<Article: Area woman programs in Python>, <Article: Third article>]
260 # Slicing works with longs.
261 >>> Article.objects.all()[0L]
262 <Article: Area woman programs in Python>
263 >>> Article.objects.all()[1L:3L]
264 [<Article: Second article>, <Article: Third article>]
265 >>> s3 = Article.objects.filter(id__exact=3)
266 >>> (s1 | s2 | s3)[::2L]
267 [<Article: Area woman programs in Python>, <Article: Third article>]
269 # And can be mixed with ints.
270 >>> Article.objects.all()[1:3L]
271 [<Article: Second article>, <Article: Third article>]
273 # Slices (without step) are lazy:
274 >>> Article.objects.all()[0:5].filter()
275 [<Article: Area woman programs in Python>, <Article: Second article>, <Article: Third article>, <Article: Article 6>, <Article: Default headline>]
277 # Slicing again works:
278 >>> Article.objects.all()[0:5][0:2]
279 [<Article: Area woman programs in Python>, <Article: Second article>]
280 >>> Article.objects.all()[0:5][:2]
281 [<Article: Area woman programs in Python>, <Article: Second article>]
282 >>> Article.objects.all()[0:5][4:]
283 [<Article: Default headline>]
284 >>> Article.objects.all()[0:5][5:]
287 # Some more tests!
288 >>> Article.objects.all()[2:][0:2]
289 [<Article: Third article>, <Article: Article 6>]
290 >>> Article.objects.all()[2:][:2]
291 [<Article: Third article>, <Article: Article 6>]
292 >>> Article.objects.all()[2:][2:3]
293 [<Article: Default headline>]
295 # Using an offset without a limit is also possible.
296 >>> Article.objects.all()[5:]
297 [<Article: Fourth article>, <Article: Article 7>, <Article: Updated article 8>]
299 # Also, once you have sliced you can't filter, re-order or combine
300 >>> Article.objects.all()[0:5].filter(id=1)
301 Traceback (most recent call last):
303 AssertionError: Cannot filter a query once a slice has been taken.
305 >>> Article.objects.all()[0:5].order_by('id')
306 Traceback (most recent call last):
308 AssertionError: Cannot reorder a query once a slice has been taken.
310 >>> Article.objects.all()[0:1] & Article.objects.all()[4:5]
311 Traceback (most recent call last):
313 AssertionError: Cannot combine queries once a slice has been taken.
315 # Negative slices are not supported, due to database constraints.
316 # (hint: inverting your ordering might do what you need).
317 >>> Article.objects.all()[-1]
318 Traceback (most recent call last):
320 AssertionError: Negative indexing is not supported.
321 >>> Article.objects.all()[0:-5]
322 Traceback (most recent call last):
324 AssertionError: Negative indexing is not supported.
326 # An Article instance doesn't have access to the "objects" attribute.
327 # That's only available on the class.
328 >>> a7.objects.all()
329 Traceback (most recent call last):
331 AttributeError: Manager isn't accessible via Article instances
333 >>> a7.objects
334 Traceback (most recent call last):
336 AttributeError: Manager isn't accessible via Article instances
338 # Bulk delete test: How many objects before and after the delete?
339 >>> Article.objects.all()
340 [<Article: Area woman programs in Python>, <Article: Second article>, <Article: Third article>, <Article: Article 6>, <Article: Default headline>, <Article: Fourth article>, <Article: Article 7>, <Article: Updated article 8>]
341 >>> Article.objects.filter(id__lte=4).delete()
342 >>> Article.objects.all()
343 [<Article: Article 6>, <Article: Default headline>, <Article: Article 7>, <Article: Updated article 8>]
344 """}
346 from django.conf import settings
348 building_docs = getattr(settings, 'BUILDING_DOCS', False)
350 if building_docs or settings.DATABASE_ENGINE == 'postgresql':
351 __test__['API_TESTS'] += """
352 # In PostgreSQL, microsecond-level precision is available.
353 >>> a9 = Article(headline='Article 9', pub_date=datetime(2005, 7, 31, 12, 30, 45, 180))
354 >>> a9.save()
355 >>> Article.objects.get(id__exact=9).pub_date
356 datetime.datetime(2005, 7, 31, 12, 30, 45, 180)
359 if building_docs or settings.DATABASE_ENGINE == 'mysql':
360 __test__['API_TESTS'] += """
361 # In MySQL, microsecond-level precision isn't available. You'll lose
362 # microsecond-level precision once the data is saved.
363 >>> a9 = Article(headline='Article 9', pub_date=datetime(2005, 7, 31, 12, 30, 45, 180))
364 >>> a9.save()
365 >>> Article.objects.get(id__exact=9).pub_date
366 datetime.datetime(2005, 7, 31, 12, 30, 45)
369 __test__['API_TESTS'] += """
371 # You can manually specify the primary key when creating a new object.
372 >>> a101 = Article(id=101, headline='Article 101', pub_date=datetime(2005, 7, 31, 12, 30, 45))
373 >>> a101.save()
374 >>> a101 = Article.objects.get(pk=101)
375 >>> a101.headline
376 u'Article 101'
378 # You can create saved objects in a single step
379 >>> a10 = Article.objects.create(headline="Article 10", pub_date=datetime(2005, 7, 31, 12, 30, 45))
380 >>> Article.objects.get(headline="Article 10")
381 <Article: Article 10>
383 # Edge-case test: A year lookup should retrieve all objects in the given
384 year, including Jan. 1 and Dec. 31.
385 >>> a11 = Article.objects.create(headline='Article 11', pub_date=datetime(2008, 1, 1))
386 >>> a12 = Article.objects.create(headline='Article 12', pub_date=datetime(2008, 12, 31, 23, 59, 59, 999999))
387 >>> Article.objects.filter(pub_date__year=2008)
388 [<Article: Article 11>, <Article: Article 12>]
390 # Unicode data works, too.
391 >>> a = Article(headline=u'\u6797\u539f \u3081\u3050\u307f', pub_date=datetime(2005, 7, 28))
392 >>> a.save()
393 >>> Article.objects.get(pk=a.id).headline
394 u'\u6797\u539f \u3081\u3050\u307f'
396 # Model instances have a hash function, so they can be used in sets or as
397 # dictionary keys. Two models compare as equal if their primary keys are equal.
398 >>> s = set([a10, a11, a12])
399 >>> Article.objects.get(headline='Article 11') in s
400 True