Django

Code

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

Revision 7914, 14.2 kB (checked in by russellm, 1 month ago)

Fixed #7718 -- Added a naive implementation of sorted() for Python 2.3 compatibility, and modified test cases to import the function when required.

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