python - Why won't Django Model's time field default properly to utcnow() as expected? -
here model:
class mymodel(models.model): timestamp = models.datetimefield(default=datetime.datetime.utcnow()) def __unicode__(self): return "mymodel id=%s @ <%s %s>" % ( self.id, self.timestamp.strftime("%h:%m:%s.000").rstrip("0").rstrip("."), self.timestamp.strftime("%m/%d/%y") ) look happens when run commands console:
>>> myapp.models import * >>> import datetime >>> mymodel() <mymodel: mymodel id=none @ <02:04:45 03/25/2014>> >>> # wait several seconds >>> mymodel() <mymodel: mymodel id=none @ <02:04:45 03/25/2014>> >>> # wait several seconds >>> mymodel() <mymodel: mymodel id=none @ <02:04:45 03/25/2014>> >>> # wait several seconds >>> mymodel(timestamp=datetime.datetime.utcnow()) <mymodel: mymodel id=none @ <02:07:16 03/25/2014>> >>> # wait several seconds >>> mymodel() <mymodel: mymodel id=none @ <02:04:45 03/25/2014>> >>> # wait several seconds >>> mymodel() <mymodel: mymodel id=none @ <02:04:45 03/25/2014>> why default value of timestamp (which supposed assigned datetime.datetime.utcnow() each mymodel) stay same first 1 created?
the time changes if manually set value in constructor ugly hack!
it looks default value getting cached , continually re-used. how prevent caching happening?
because you've called it. pass function instead.
timestamp = models.datetimefield(default=datetime.datetime.utcnow)
Comments
Post a Comment