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.
8
This example uses ``datetime.datetime.now`` as the default for the ``pub_date``
12
from django.db import models
13
from datetime import datetime
15
class Article(models.Model):
16
headline = models.CharField(max_length=100, default='Default headline')
17
pub_date = models.DateTimeField(default=datetime.now)
19
def __unicode__(self):
22
__test__ = {'API_TESTS':"""
23
>>> from datetime import datetime
25
# No articles are in the system yet.
26
>>> Article.objects.all()
30
>>> a = Article(id=None)
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()
36
# Save it into the database. You have to call save() explicitly.
39
# Now it has an ID. Note it's a long integer, as designated by the trailing "L".
43
# Access database columns via Python attributes.
47
# make sure the two dates are sufficiently close
48
>>> d = now - a.pub_date
52
# make sure that SafeString/SafeUnicode fields work
53
>>> from django.utils.safestring import SafeUnicode, SafeString
54
>>> a.headline = SafeUnicode(u'SafeUnicode Headline')
56
>>> a.headline = SafeString(u'SafeString Headline')