Ticket #1409: field_defaults.diff

File field_defaults.diff, 2.0 KB (added by jkocherhans, 19 years ago)
  • django/db/models/fields/__init__.py

     
    163163    def get_default(self):
    164164        "Returns the default value for this field."
    165165        if self.default != NOT_PROVIDED:
    166             if hasattr(self.default, '__get_value__'):
    167                 return self.default.__get_value__()
     166            if callable(self.default):
     167                return self.default()
    168168            return self.default
    169169        if not self.empty_strings_allowed or self.null:
    170170            return None
  • tests/modeltests/field_defaults/models.py

     
     1"""
     2XXX. Callable defaults
     3
     4???
     5"""
     6
     7from django.db import models
     8from datetime import datetime
     9
     10class Article(models.Model):
     11    headline = models.CharField(maxlength=100, default='Default headline')
     12    pub_date = models.DateTimeField(default = datetime.now)
     13   
     14    def __repr__(self):
     15        return self.headline
     16
     17API_TESTS = """
     18>>> from datetime import datetime
     19
     20# No articles are in the system yet.
     21>>> Article.objects.all()
     22[]
     23
     24# Create an Article.
     25>>> a = Article(id=None)
     26
     27# Grab the current datetime it should be very close to the default that just
     28# got saved as a.pub_date
     29>>> now = datetime.now()
     30
     31# Save it into the database. You have to call save() explicitly.
     32>>> a.save()
     33
     34# Now it has an ID. Note it's a long integer, as designated by the trailing "L".
     35>>> a.id
     361L
     37
     38# Access database columns via Python attributes.
     39>>> a.headline
     40'Default headline'
     41
     42# make sure the two dates are sufficiently close
     43>>> d = now - a.pub_date
     44>>> d.seconds < 5
     45True
     46
     47
     48"""
Back to Top