equal
deleted
inserted
replaced
1 """ |
|
2 32. Callable defaults |
|
3 |
|
4 You can pass callable objects as the ``default`` parameter to a field. When |
|
5 the object is created without an explicit value passed in, Django will call |
|
6 the method to determine the default value. |
|
7 |
|
8 This example uses ``datetime.datetime.now`` as the default for the ``pub_date`` |
|
9 field. |
|
10 """ |
|
11 |
|
12 from django.db import models |
|
13 from datetime import datetime |
|
14 |
|
15 class Article(models.Model): |
|
16 headline = models.CharField(maxlength=100, default='Default headline') |
|
17 pub_date = models.DateTimeField(default=datetime.now) |
|
18 |
|
19 def __str__(self): |
|
20 return self.headline |
|
21 |
|
22 __test__ = {'API_TESTS':""" |
|
23 >>> from datetime import datetime |
|
24 |
|
25 # No articles are in the system yet. |
|
26 >>> Article.objects.all() |
|
27 [] |
|
28 |
|
29 # Create an Article. |
|
30 >>> a = Article(id=None) |
|
31 |
|
32 # Grab the current datetime it should be very close to the default that just |
|
33 # got saved as a.pub_date |
|
34 >>> now = datetime.now() |
|
35 |
|
36 # Save it into the database. You have to call save() explicitly. |
|
37 >>> a.save() |
|
38 |
|
39 # Now it has an ID. Note it's a long integer, as designated by the trailing "L". |
|
40 >>> a.id |
|
41 1L |
|
42 |
|
43 # Access database columns via Python attributes. |
|
44 >>> a.headline |
|
45 'Default headline' |
|
46 |
|
47 # make sure the two dates are sufficiently close |
|
48 >>> d = now - a.pub_date |
|
49 >>> d.seconds < 5 |
|
50 True |
|
51 """} |
|