这是我的模特:
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")
)
看看当我从控制台运行一些命令时会发生什么:
>>> 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>>
为什么timeStamp的默认值(应该为每个MyModel分配给datetime.datetime.utcnow())与我创建的第一个默认值保持一致?
如果我在构造函数中手动设置了一个丑陋的黑客,那么它唯一的变化!
看起来默认值是缓存并不断重复使用。如何防止此缓存发生?
答案 0 :(得分:1)
因为你已经打电话了。将其作为函数传递。
timeStamp = models.DateTimeField(default=datetime.datetime.utcnow)