Question

Here is my Model:

class MyModel(models.Model):
    timeStamp = models.DateTimeField(default=datetime.datetime.utcnow())
    def __unicode__(self):
        return "MyModel ID=%s at <%s %s>" % (
            self.id, 
            self.timeStamp.strftime("%H:%M:%S.000").rstrip("0").rstrip("."), 
            self.timeStamp.strftime("%m/%d/%Y")
        )

Look what happens when I run some commands from the console:

>>> from MyApp.models import *
>>> import datetime

>>> MyModel()
<MyModel: MyModel ID=None at <02:04:45 03/25/2014>>

>>> # Wait several seconds
>>> MyModel()
<MyModel: MyModel ID=None at <02:04:45 03/25/2014>>

>>> # Wait several seconds
>>> MyModel()
<MyModel: MyModel ID=None at <02:04:45 03/25/2014>>


>>> # Wait several seconds
>>> MyModel(timeStamp=datetime.datetime.utcnow())
<MyModel: MyModel ID=None at <02:07:16 03/25/2014>>

>>> # Wait several seconds
>>> MyModel()
<MyModel: MyModel ID=None at <02:04:45 03/25/2014>>

>>> # Wait several seconds
>>> MyModel()
<MyModel: MyModel ID=None at <02:04:45 03/25/2014>>

Why does the default value of timeStamp (which is supposed to be assigned to datetime.datetime.utcnow() for each MyModel) stay the same as the first one I created?

The only time it changes if I manually set that value in the constructor which is an ugly hack!

It looks like the default value is getting cached and continually re-used. How do I prevent this caching from happening?

Was it helpful?

Solution

Because you've already called it. Pass it as a function instead.

timeStamp = models.DateTimeField(default=datetime.datetime.utcnow)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top