2015-10-07 38 views
3

當我插入一行時,該字段被填滿了服務器啓動的時間,而不是該行插入的時間。爲什麼會發生這種情況,解決方案是什麼?順便說一句,我正在使用SQLite。在Peewee我有一個日期時間字段默認datetime.datetime.now()。但插入時,服務器啓動需要花費時間。爲什麼

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. 

回答

-4

它走的是編譯時間(沒有測試)

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) 

似乎這 is there an auto update option for DateTimeField in peewee like TimeStamp in MySQL?

複製(在服務器啓動的時間)

覆蓋的保存方法

+1

這是不完全正確。 Peewee支持可調參數,所以你可以說'default = datetime.datetime.now'(沒有括號)。 – coleifer

13

當您的字段由Python解釋器加載時,它只會調用datetime.datetime.now()一次。所以你將永遠得到相同的價值。

Peewee支持使用可調用默認ARGS,所以而非調用 NOW()只是傳遞中的作用:

timestamp = peewee.DateTimeField(default=datetime.datetime.now) 
+0

如何使用服務器端時間戳? – warvariuc

+0

Found:'timestamp = DateTimeField(constraints = [SQL('DEFAULT CURRENT_TIMESTAMP')])' – warvariuc

-2

應該這樣做。重寫保存方法

class myModel(Model): 

    name = CharField() 
    timestamp = DateTimeField() 

    def save(self, *args, **kwargs): 
     self.timestamp = datetime.datetime.now() 
     super(myModel, self).save(*args, **kwargs) 

工作正常後,此修復

+0

這解釋了實例化和保存之間存在差距的情況,但不是上面的例子,他將默認設置爲datetime.datetime.now()的值(在模塊代碼加載時調用),而不是可調用的datetime.datetime.now。 – coleifer

相關問題