2015-06-06 23 views
0

我有一個Comment模型。它具有以下時間戳字段:Django的DateTimeField的「auto_now」似乎不起作用

created = models.DateTimeField(auto_now_add=True, blank=True, null=True) 
last_edit = models.DateTimeField(auto_now=True, blank=True, null=True) 

現在,當我使用這種格式更新評論:Comment.objects.filter(...).update(text="some new text"),在last_edit領域沒有得到,而註釋的文本也得到更新更新。有什麼問題?

更新:此外,我正在使用filter,因爲update不適用於get,即Comment.objects.get(...).update(...)不起作用。我實際上想要做的是get,因爲我確信只有一條評論需要一次更新。

回答

2

因爲您使用的是update,它直接在數據庫中進行更新,而auto_now是在Python中完成的。這將工作:

for commment in Comment.objects.filter(...): 
    comment.text="some new text" 
    comment.save() 

很明顯,這是不是一次性去做數據庫的效率。如果你真的需要這個,那麼你必須在更新中設置日期:

Comment.objects.filter(...).update(text="some new text", last_edit=datetime.datetime.now())