[英]In Peewee I have a datetime field defaulted to datetime.datetime.now(). But when inserted, it takes the time the server was started. Why
When I insert a row, the field is filled with the time when the server was started not the time when the row was inserted. 当我插入一行时,该字段将填充服务器启动的时间而不是插入行的时间。 Why is this happening and what is the solution?
为什么会发生这种情况,解决方案是什么? BTW I am using SQLite.
顺便说一下,我正在使用SQLite。
class LOG(peewee.Model):
id = peewee.IntegerField(unique=True,primary_key=True)
timestamp = peewee.DateTimeField(default=datetime.datetime.now())
log = peewee.CharField()
by = peewee.IntegerField(default=1)
class Meta:
database = database
LOG.create(log = _log , by = _by)
# above statement is called at say 3:00 pm and I started the server at 2:00 pm, then the row is inserted with timestamp of 2pm not 3pm.
When your field is loaded by the Python interpreter, it calls datetime.datetime.now()
once and only once. 当您的字段由Python解释器加载时,它只调用
datetime.datetime.now()
一次。 So you will always get the same value. 所以你总会获得相同的价值。
Peewee supports using callables for default args, so rather than calling now() just pass in the function: Peewee支持使用callables作为默认args,所以不要只调用 now()来传递函数:
timestamp = peewee.DateTimeField(default=datetime.datetime.now)
It should be done like this. 它应该这样做。 Override the save method
覆盖save方法
class myModel(Model):
name = CharField()
timestamp = DateTimeField()
def save(self, *args, **kwargs):
self.timestamp = datetime.datetime.now()
super(myModel, self).save(*args, **kwargs)
Works fine after this fix 修复后工作正常
It is taking the compiled time (the time when the server was started) 它是在编译时间(服务器启动的时间)
[edited] because you have used datetime.datetime.now()
(with parenthesis) As suggested by @coleifer you can use datetime.datetime.now
(without paranthesis) to initiate a run-time call. [编辑],因为你已经使用了
datetime.datetime.now()
(带括号)正如@coleifer所建议你可以使用datetime.datetime.now
(没有paranthesis)来启动运行时调用。
[old answer] Overriding the save method will also work [旧答案]覆盖保存方法也可以
class LOG(peewee.Model):
id = peewee.IntegerField(unique=True,primary_key=True)
timestamp = peewee.DateTimeField()
log = peewee.CharField()
by = peewee.IntegerField(default=1)
class Meta:
database = database
def save(self, *args, **kwargs):
self.modified = datetime.datetime.now()
return super(Something, self).save(*args, **kwargs)
Seems Duplicate of this is there an auto update option for DateTimeField in peewee like TimeStamp in MySQL? 看起来重复这是在MySQL中像TimeStamp这样的peewee中有DateTimeField的自动更新选项吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.