问题
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.
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.
回答1:
When your field is loaded by the Python interpreter, it calls datetime.datetime.now()
once and only once. 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:
timestamp = peewee.DateTimeField(default=datetime.datetime.now)
回答2:
It should be done like this. Override the save method
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
回答3:
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.
[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?
来源:https://stackoverflow.com/questions/32990080/in-peewee-i-have-a-datetime-field-defaulted-to-datetime-datetime-now-but-when